我有一个数组字典
{1:array([...]), 2:array([...]), 3:array([...])}
Run Code Online (Sandbox Code Playgroud)
我想将它保存到一个文件中,稍后再加载。
我发现一个 numpy 有一个输入和输出方法的列表,但似乎它们只处理数组。
谢谢。
小智 8
以下脚本将 numpy 数组的 dict 保存到磁盘,然后将其加载回内存。
import numpy as np
arr1 = np.arange(0, 10, 1)
arr2 = np.arange(10, 20, 1)
arr3 = np.arange(20, 30, 1)
dct = {'1': arr1, '2': arr2, '3':arr3}
outfile = 'dict_of_arrays.npz'
np.savez(outfile, **dct)
npzfile = np.load(outfile)
print('npzfile.files: {}'.format(npzfile.files))
print('npzfile["1"]: {}'.format(npzfile["1"]))
Run Code Online (Sandbox Code Playgroud)
运行此脚本显示以下内容:
npzfile.files: ['1', '3', '2']
npzfile["1"]: [0 1 2 3 4 5 6 7 8 9]
Run Code Online (Sandbox Code Playgroud)
请注意,您的 dict 键必须是字符串。也许这就是问题所在?
我正在运行 numpy 1.10.4
实际上,您可以使用内置pickle库来序列化和反序列化对象,而无需使用 numpy。
这是一个模拟代码
import pickle
data1 = {'a': [1, 2.0, 3, 4 + 6j],
'b': ('string', u'Unicode string'),
'c': None}
print data1, type(data1)
with open('data.pkl', 'wb') as output:
# Pickle dictionary using protocol 0.
pickle.dump(data1, output)
# load data from pkl file
with open("data.pkl", "rb") as fp:
loaded_data1 = pickle.load(fp)
print loaded_data1, type(loaded_data1)
Run Code Online (Sandbox Code Playgroud)
结果
Before: {'a': [1, 2.0, 3, (4+6j)], 'c': None, 'b': ('string', u'Unicode string')} <type 'dict'>
After: {'a': [1, 2.0, 3, (4+6j)], 'c': None, 'b': ('string', u'Unicode string')} <type 'dict'>
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。