Python:通过numpy.s保存字典

2024-05-12 15:57:26 发布

您现在位置:Python中文网/ 问答频道 /正文

内存中有一个大数据集(数百万行),其形式是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'

Tags: 文件数据内存innumpyget字典save
2条回答

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

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对象保存在单个pickled文件中。在这种情况下,每个pickle.load调用都将加载一个对象。

它是一个结构化数组。使用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]

相关问题 更多 >