Ale*_*ara 5 python dictionary numpy multidimensional-array
如何有效地编写 Python 字典,其中值是 Numpy Nd-Arrays 到 Json 文件?我收到一条错误消息,指出 Numpy Nd-Array 不是 Json-Serializable。有什么办法可以克服这个问题吗?
JSON 仅支持有限数量的数据类型。如果要将其他类型的数据存储为 JSON,则需要将其转换为 JSON 接受的数据。Numpy 数组的明显选择是将它们存储为(可能是嵌套的)列表。幸运的是,Numpy 数组有一种.tolist
可以有效执行转换的方法。
import numpy as np
import json
a = np.array(range(25), dtype=np.uint8).reshape(5, 5)
print(a)
print(json.dumps(a.tolist()))
Run Code Online (Sandbox Code Playgroud)
输出
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]
Run Code Online (Sandbox Code Playgroud)
.tolist
如果可以无损地将数组元素转换为原生 Python 类型(int 或 float)。如果您使用其他数据类型,我建议您在调用之前将它们转换为可移植的数据类型.tolist
。