Python : save dictionaries through numpy. 保存

标签 python numpy dictionary

我在内存中有一个大型数据集(数百万行),采用 numpy 数组字典 的形式。

一旦构建了这些数据,我想将它们存储到文件中; 因此,稍后我可以将这些文件快速加载到内存中,而无需再次从头开始重建这些数据。

np.savenp.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/

相关文章:

python - 使用 numpy 从文件中读取字符串中的 float

java - 如何在 Java 中按值(ArrayList)大小对 map 进行排序?

python - 加快查找两个词典之间的匹配项 (Python)

python - 我将如何编写 NumPy argmode()?

python - numpy dot()和内()之间的差异

python - 在无堆栈 Python 中,您可以通过 channel 发送 channel 吗?

python - 在 Django 表单中获取上一个 URL

python - 如何拥有一个没有距离较近的元素对的数组

python - 多个二项式随机变量的向量化采样

list - Flutter:通用列表处理不同的键值对