【问题标题】:Numpy np.fromstring() not working as hopedNumpy np.fromstring() 没有按预期工作
【发布时间】:2019-01-25 15:00:23
【问题描述】:

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

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.01s 的数组

【问题讨论】:

  • arr.tolist() 可以保存为 JSON,保留括号的嵌套。

标签: python numpy type-conversion


【解决方案1】:

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

【讨论】:

  • 快速正确的@yatu 谢谢。这么快就接受答案是正确的礼仪还是应该让它慢一点?顺便说一句,我也在巴萨……
  • 好吧@seanysull,这取决于您期望的答案类型,但IMO这是针对此特定问题的最简单解决方案。很高兴知道! (虽然巴塞罗那,在这里我们只称巴萨为足球队,而不是城市:-)
  • 两个答案都是正确的。这个答案,但我的输入是这种格式,我无法让时钟倒转。另一个是未来应该怎么做。尽管 fromstring 不处理括号,但我确实觉得很奇怪。他们在考虑什么用例?
  • 不知道,大概是 Cristi 指出的数组没有正确序列化@demongolem
【解决方案2】:

很可能,您使用 str 将数组保存在文件中。那是错误的。
虽然在这种情况下,错误是不可见的,但对于较大的数组,很明显以这种方式保存的值会产生不正确的缓冲区。更多详情请查看[SO]: ValueError: sequence too large; cannot be greater than 32 (@CristiFati's answer)

虽然有一些简单的方法可以克服当前的情况(对现有字符串进行额外处理),但它们只是解决方法 (gainarii),而正确的方法(或者,至少一种他们)要解决的方法是在将数组保存到文件时正确序列化数组(使用[SciPy.Docs]: numpy.ndarray.tostring)。

>>> arr = np.array([0.01, 0.01, 0.01, 0.01, 0.01, 0.01])
>>> arr
array([0.01, 0.01, 0.01, 0.01, 0.01, 0.01])
>>>
>>> str_arr0 = str(arr)
>>> str_arr0
'[0.01 0.01 0.01 0.01 0.01 0.01]'
>>> str_arr1 = arr.tostring()
>>> str_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?'
>>>
>>> arr_final = np.fromstring(str_arr1, dtype=np.float64)
>>> arr_final
array([0.01, 0.01, 0.01, 0.01, 0.01, 0.01])
>>>
>>> arr_final_wrong = np.fromstring(str_arr0[1:-1], dtype=np.float64, count=6, sep= " ")
>>> arr_final_wrong
array([0.01, 0.01, 0.01, 0.01, 0.01, 0.01])
>>>
>>> arr = np.array([0.01, 0.01, 0.01, 0.01, 0.01, 0.01] * 10)
>>> # This time, str(arr) will produce an invalid result
...
>>> str(arr)
'[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\n 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\n 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\n 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\n 0.01 0.01 0.01 0.01]'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 2021-10-19
    • 2020-03-18
    • 2012-06-14
    • 2014-11-15
    • 1970-01-01
    • 2012-07-02
    • 2011-09-07
    相关资源
    最近更新 更多