简体   繁体   English

Numpy 从字符串解析为 ndarray

[英]Numpy parse to ndarray from string

I have stringified ndarray passed from server to the client-side, the example of that array could be seen below我已经将 ndarray 从服务器传递到客户端,该数组的示例如下所示

import numpy as np

str_array = "[[0.1233 0.333 4.1111] [0.1233 0.333 4.1111] [0.1233 0.333 4.1111]]"
arr = np.fromstring(str_array, dtype=np.float32, sep = ' ')

print(arr)

when I run that code, it would raise an error message:当我运行该代码时,它会引发错误消息:

  File "example.py", line 89, in <module>
    arr = np.fromstring(str_array, dtype=np.float32)
ValueError: string size must be a multiple of element size

I want my stringified array to become a ndarray again.我希望我的字符串化数组再次成为一个 ndarray。 How can I solve this?我该如何解决这个问题?

Use numpy.matrix and than reshape使用numpy.matrix而不是reshape

>>> np.matrix(str_array).reshape(-1,3)
matrix([[0.1233, 0.333 , 4.1111],
        [0.1233, 0.333 , 4.1111],
        [0.1233, 0.333 , 4.1111]])

Or to get ndarray use attribute matrix.A或者获取ndarray使用属性matrix.A

>>> np.matrix(str_array).reshape(-1,3).A
array([[0.1233, 0.333 , 4.1111],
       [0.1233, 0.333 , 4.1111],
       [0.1233, 0.333 , 4.1111]])

I note that the documentation says that np.fromstring() "Return a new 1-D array initialized from raw binary or text data in string."我注意到文档np.fromstring() “返回一个从原始二进制或字符串中的文本数据初始化的新一维数组。”

If you know the dimensions of your array, one simple workaround for the fact your data is 2D would simply to be:如果您知道数组的维度,那么对于您的数据是 2D 的事实的一种简单解决方法就是:

str_array = str_array.replace("]", "")
str_array = str_array.replace("[", "")
np.fromstring(str_array, sep=' ').reshape(3,3)

Which does yield:这确实产生:

array([[0.1233, 0.333 , 4.1111],
       [0.1233, 0.333 , 4.1111],
       [0.1233, 0.333 , 4.1111]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM