【发布时间】:2019-09-10 13:13:12
【问题描述】:
我有一个浮点数数组,我希望将其转换为字符串以通过 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 数组。我尝试过使用以下内容,但我没有感到高兴:
a = np.fromstring(numbers_to_string_commas, dtype=np.float64, sep=',')
print(a)
[]
我该怎么做?
【问题讨论】:
-
您可以搜索
numpy和json,但我建议您使用numbers.tolist(),并使用json对该(嵌套)列表进行编码。反面是np.array(json.loads(...))。tolist速度很快,json可以很好地处理数字列表。
标签: python-3.x numpy numpy-ndarray