Convert string containg array of floats to numpy array

北战南征 提交于 2019-12-11 18:25:30

问题


I have a numpy array of floats that I wish to convert to a string to transmit via JSON:

import numpy as np
#Create an array of float arrays
numbers = np.array([[1.0, 2.0],[3.0,4.0],[5.0,6.0]], dtype=np.float64)
print(numbers)
[[1. 2.]
 [3. 4.]
 [5. 6.]]

#Convert each row in the array to string and separate by a ','
numbers_to_string_commas = ','.join(str(number) for number in numbers)
print(numbers_to_string_commas)
[1. 2.],[3. 4.],[5. 6.]

Now I wish to convert this string back into the original numpy array. I have tried using the following but I have had no joy:

a = np.fromstring(numbers_to_string_commas, dtype=np.float64, sep=',')
print(a)
[]

How can I do this?


回答1:


I think the problem is that the format is not quite the formats that numpy is expecting, but if the string is not too huge:

In [39]: eval('np.array([%s])' % '[1. 2.],[3. 4.],[5. 6.]'.replace(' ', ','))
Out[39]: 
array([[1., 2.],
       [3., 4.],
       [5., 6.]])

Be aware if the string is very long you might run into issues: Why is there a length limit to python's eval?




回答2:


Maybe you could modify your "numbers_to_string_commas" a little to make rereading easier. Here's another solution:

a=np.matrix(numbers_to_string_commas.replace(',',' ').replace('] [',';')[1:-1])
>>> a
matrix([[ 1.,  2.],
        [ 3.,  4.],
        [ 5.,  6.]])

This seems to do what you wanted.



来源:https://stackoverflow.com/questions/57871598/convert-string-containg-array-of-floats-to-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!