【发布时间】:2021-03-05 15:57:32
【问题描述】:
如何将以下字符串转换为 numpy 浮点数组
'[[1.45757244e+03 0.00000000e+00 1.21294569e+03]
[0.00000000e+00 1.45752223e+03 1.00732059e+03]
[0.00000000e+00 0.00000000e+00 1.00000000e+00]]'
这是一种方法,但它很难拆分连续的 '[' 以使 cols 变量
def str2num(str_in, np_type, shape):
names_list = str_in.splitlines()
tem = []
for row in names_list:
is_str = isinstance(row, str)
if is_str:
cols = [s for s in row.split(string.whitespace+'[], ') if s]
for col in cols:
tem.append(col)
tem = flatten(tem)
return np.array(tem, dtype=np_type).reshape(shape)
【问题讨论】:
-
哎呀!你是怎么得到的?数组的打印字符串是为转换回来而设计的。缺少逗号意味着它不能被评估为一个列表(列表)。并且 [] 妨碍了在空白处简单分割。
-
伟大的 cmets,也许我应该用逗号替换东西,甚至将其转换为用逗号分隔的字符串列表。我会将我的代码添加到问题中。我把代码省略了,因为我不确定我是否走在正确的道路上。
-
这种情况最常出现的上下文是在加载一个
pandas数据框csv,该数据框在单个单元格中具有数组。pandas只能将str(array)写入csv,然后将其作为字符串加载。
标签: python arrays string numpy