我已将一个数组作为字符串保存在文本文件中,希望在从文件读取时能够将其转换回数组:
str_arr = "[0.01 0.01 0.01 0.01 0.01 0.01]"
num_arr = np.fromstring(str_arr,dtype = np.float64 ,count = 6,sep = ' ')
whic 的结果是 num_array
:
array([-1.00000000e+000, 6.94819184e-310, 6.94819184e-310,
6.94818751e-310, 6.94818751e-310, 6.94818751e-310])
我期待一个 0.01
的数组
最佳答案
似乎np.fromstring
不知道如何解释括号。您可以通过在调用函数之前剥离它们来解决这个问题:
a = "[0.01 0.01 0.01 0.01 0.01 0.01]"
num_arr = np.fromstring(a.strip('[]'), count = 6, sep = ' ')
array([0.01, 0.01, 0.01, 0.01, 0.01, 0.01])
另请注意,dtype
默认为 float
,因此在这种情况下无需指定。
关于python - Numpy np.fromstring() 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54367816/