我在内存中有一个大型数据集(数百万行),采用 numpy 数组 和 字典 的形式。
一旦构建了这些数据,我想将它们存储到文件中; 因此,稍后我可以将这些文件快速加载到内存中,而无需再次从头开始重建这些数据。
np.save 和 np.load 函数可以顺利完成 numpy 数组的工作。
但我面临 dict 对象的问题。
请参见下面的示例。 d2 是从文件中加载的字典。 请参阅#out[28],它已作为 numpy 数组而不是 dict 加载到 d2 中。因此进一步的 dict 操作(例如 get)不起作用。
有没有办法将文件中的数据加载为 dict(而不是 numpy 数组)?
In [25]: d1={'key1':[5,10], 'key2':[50,100]}
In [26]: np.save("d1.npy", d1)
In [27]: d2=np.load("d1.npy")
In [28]: d2
Out[28]: array({'key2': [50, 100], 'key1': [5, 10]}, dtype=object)
In [30]: d1.get('key1') #original dict before saving into file
Out[30]: [5, 10]
In [31]: d2.get('key2') #dictionary loaded from the file
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-31-23e02e45bf22> in <module>()
----> 1 d2.get('key2')
AttributeError: 'numpy.ndarray' object has no attribute 'get'
最佳答案
这是一个结构化数组。首先使用 d2.item()
检索实际的 dict 对象:
import numpy as np
d1={'key1':[5,10], 'key2':[50,100]}
np.save("d1.npy", d1)
d2=np.load("d1.npy")
print d1.get('key1')
print d2.item().get('key2')
结果:
[5, 10]
[50, 100]
关于Python : save dictionaries through numpy. 保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40219946/