简体   繁体   中英

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

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. How can I solve this?

Use numpy.matrix and than 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

>>> 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."

If you know the dimensions of your array, one simple workaround for the fact your data is 2D would simply to be:

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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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