Numpy parse to ndarray from string

asrulsibaoel :

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?

Dishin H Goyani :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=346204&siteId=1