Python:通过numpy.save保存字典

ram*_*amu 23 python dictionary numpy

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

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

np.savenp.load函数可以为numpy数组顺利完成工作.
但是我遇到了dict对象的问题.

见下面的样本.d2是从文件加载的字典.请参阅#out [28]它已作为numpy数组加载到d2中,而不是作为dict.所以进一步的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'
Run Code Online (Sandbox Code Playgroud)

Ken*_*ste 51

这是一个结构化的数组.用于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')
Run Code Online (Sandbox Code Playgroud)

结果:

[5, 10]
[50, 100]
Run Code Online (Sandbox Code Playgroud)

  • @Albert 做`np.load(“d1.npy”,allow_pickle = True)` (4认同)
  • d2.item() 完美运行。谢谢。 (3认同)

Kh4*_*tiK 5

可以使用泡菜模块。示例代码:

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'])
Run Code Online (Sandbox Code Playgroud)

您也可以将多个python对象保存在一个腌制的文件中。pickle.load在这种情况下,每个调用将加载一个对象。