Python Numpy np.fromstring()未按预期工作

Python Numpy np.fromstring()未按预期工作,python,numpy,type-conversion,Python,Numpy,Type Conversion,我已将数组保存在文本文件中作为字符串,希望在从文件读取时能够将其转换回数组: 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 = ' ') 其结果是num\u数组: array([-1.00000000e+000, 6.94819184e-310, 6.94819184e-310, 6.94818751e

我已将数组保存在文本文件中作为字符串,希望在从文件读取时能够将其转换回数组:

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 = ' ')
其结果是
num\u数组

array([-1.00000000e+000,  6.94819184e-310,  6.94819184e-310,
        6.94818751e-310,  6.94818751e-310,  6.94818751e-310])
我期待的是一个
0.01
s

的数组,它似乎不知道如何解释括号。您可以通过在调用函数之前剥离它们来解决此问题:

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
,因此在这种情况下不需要指定它。

很可能是您使用str将数组保存在文件中。这是错误的
虽然在这种情况下,错误不可见,但对于较大的数组,很明显,以这种方式保存的值将产生不正确的缓冲区。查看更多详细信息

尽管有一些简单的方法可以克服当前情况(对现有字符串进行额外处理),但它们只是解决方法(Gainari),而正确的解决方法(或至少其中一种)是在将数组保存到文件时正确序列化数组

arr=np.数组([0.01,0.01,0.01,0.01,0.01,0.01,0.01]) >>>啊 数组([0.01,0.01,0.01,0.01,0.01,0.01,0.01]) >>> >>>str_arr0=str(arr) >>>STRU arr0 '[0.01 0.01 0.01 0.01 0.01 0.01]' >>>str_arr1=arr.tostring() >>>STRU arr1 b'{\x14\xaeG\xe1z\x84?{\x14\xaeG\xe1z\x84?{\x14\xaeG\xe1z\x84?{\x14\xaeG\xe1z\x84?{\x14\xaeG\xe1z\x84?{\x14\xaeG\xe1z\x84?{\x14\xaeG\xe1z\x84?' >>> >>>arr\u final=np.fromstring(str\u arr1,dtype=np.float64) >>>阿鲁决赛 数组([0.01,0.01,0.01,0.01,0.01,0.01,0.01]) >>> >>>arr\u final\u error=np.fromstring(str\u arr0[1:-1],dtype=np.float64,count=6,sep=”“) >>>arr_final_错了 数组([0.01,0.01,0.01,0.01,0.01,0.01,0.01]) >>> >>>arr=np.数组([0.01,0.01,0.01,0.01,0.01,0.01]*10) >>>#这一次,str(arr)将产生无效结果 ... >>>str(arr) 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0“”
快速正确@yatu谢谢。这么快接受回答是正确的礼仪还是我应该让它酝酿一段时间?顺便说一句,我也在巴萨……好吧@seanysull这取决于你期望的答案,但我认为这是解决这个具体问题的最简单的方法。很高兴知道!(尽管巴塞罗那,我们这里只称巴萨为足球队,而不是城市:-)两个答案都是正确的。这一个答案是正确的,但我的输入是这种格式的,我不能让时间倒转。另一个答案是将来应该怎么做。我确实觉得奇怪,尽管fromstring不处理括号。他们考虑了什么使用案例?不知道,可能数组没有正确地序列化为Cristi points out@demongolem
arr.tolist()
可以另存为JSON,保留括号的嵌套。