我的内存中有一个大数据集(数百万行),其形式是numpy数组和字典。
一旦构建了这些数据,我希望将它们存储到文件中;因此,以后我可以快速地将这些文件加载到内存中,而无需从头开始重新构建这些数据。
np.save和np.load函数为numpy数组顺利地完成了工作。
但我正面临着有关dict对象的问题。
见下面的样品。d2是从文件中加载的字典。参见# not 28它已作为numpy数组加载到d2中,而不是作为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'
发布于 2016-10-24 13:56:45
这是一个结构化数组。首先使用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]
发布于 2016-10-24 14:00:02
可以使用泡菜模块。示例代码:
from six.moves import cPickle as pickle #for performance
from __future__ import print_function
import numpy as np
def save_dict(di_, filename_):
with open(filename_, 'wb') as f:
pickle.dump(di_, f)
def load_dict(filename_):
with open(filename_, 'rb') as f:
ret_di = pickle.load(f)
return ret_di
if __name__ == '__main__':
g_data = {
'm':np.random.rand(4,4),
'n':np.random.rand(2,2,2)
}
save_dict(g_data, './data.pkl')
g_data2 = load_dict('./data.pkl')
print(g_data['m'] == g_data2['m'])
print(g_data['n'] == g_data2['n'])
您还可以将多个python对象保存在一个被腌制的文件中。在这种情况下,每个pickle.load
调用将加载一个对象。
https://stackoverflow.com/questions/40219946
复制相似问题