将浮点数的字符串containsg数组转换为numpy数组 [英] Convert string containg array of floats to numpy array
本文介绍了将浮点数的字符串containsg数组转换为numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个浮点数数组,希望将其转换为通过JSON传输的字符串:
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.]
现在,我希望将此字符串转换回原始的numpy数组.我尝试使用以下方法,但没有任何乐趣:
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)
[]
我该怎么做?
推荐答案
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.]])
请注意,如果字符串很长,您可能会遇到问题: 为什么对python的eval有长度限制?
Be aware if the string is very long you might run into issues: Why is there a length limit to python's eval?
这篇关于将浮点数的字符串containsg数组转换为numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文