Python 将numpy数组保存为字典

Python 将numpy数组保存为字典,python,arrays,numpy,dictionary,Python,Arrays,Numpy,Dictionary,我正在将2个Numpy数组保存为字典。 当我从二进制文件加载数据时,我得到另一个ndarray。我可以将加载的Numpy数组用作字典吗? 以下是我的代码和脚本的输出: import numpy as np x = np.arange(10) y = np.array([100, 101, 102, 103, 104, 105, 106, 107]) z = {'X': x, 'Y': y} np.save('./data.npy', z) z1 = np.load('./data.npy'

我正在将2个Numpy数组保存为字典。
当我从二进制文件加载数据时,我得到另一个
ndarray
。我可以将加载的Numpy数组用作字典吗?

以下是我的代码和脚本的输出:

import numpy as np

x = np.arange(10)
y = np.array([100, 101, 102, 103, 104, 105, 106, 107])
z = {'X': x, 'Y': y}
np.save('./data.npy', z)
z1 = np.load('./data.npy')
print(type(z1))
print(z1)
print(z1['X']) #this line will generate an error
输出:{'X':数组([0,1,2,3,4,5,6,7,8,9]),'Y':数组([100,101,102,103,104,105,106,107])


是的,您可以访问0维数组中的基础字典。试试
z1[()]

下面是一个演示:

np.save('./data.npy', z)
d = np.load('./data.npy')[()]

print(type(d))
<class 'dict'>

print(d['X'])
[0 1 2 3 4 5 6 7 8 9]
import h5py, numpy as np

x = np.arange(10)
y = np.array([100, 101, 102, 103, 104, 105, 106, 107])
z = {'X': x, 'Y': y}

with h5py.File('file.h5', 'w', libver='latest') as f:  # use 'latest' for performance
    for k, v in z.items():
        f.create_dataset('dict/'+str(k), data=v)

with h5py.File('file.h5', 'r', libver='latest') as f:
    x_read = f['dict']['X'][:]  # [:] syntax extracts numpy array into memory
    y_read = f['dict']['Y'][:]

print(x_read)

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.save('./data.npy',z)
d=np.load('./data.npy')[()]
印刷品(d类)
打印(d['X'])
[0 1 2 3 4 5 6 7 8 9]

z1
访问数据的另一个选项应该是:

z1.flatten()[0]['X']

HDF5是存储
numpy
阵列的另一种未充分使用的方法。好处是:

  • 可移植性,即与Python无关,如
    pickle
  • 能够访问内存外的数据&优化的分块选项
  • 用于优化读写性能的压缩选项
下面是一个演示:

np.save('./data.npy', z)
d = np.load('./data.npy')[()]

print(type(d))
<class 'dict'>

print(d['X'])
[0 1 2 3 4 5 6 7 8 9]
import h5py, numpy as np

x = np.arange(10)
y = np.array([100, 101, 102, 103, 104, 105, 106, 107])
z = {'X': x, 'Y': y}

with h5py.File('file.h5', 'w', libver='latest') as f:  # use 'latest' for performance
    for k, v in z.items():
        f.create_dataset('dict/'+str(k), data=v)

with h5py.File('file.h5', 'r', libver='latest') as f:
    x_read = f['dict']['X'][:]  # [:] syntax extracts numpy array into memory
    y_read = f['dict']['Y'][:]

print(x_read)

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

我使用
pickle
保存字典。它真的很容易使用。。。什么错误?您是否注意到在生成错误时使用大写Z而不是Z?
np.save
保存数组。如果给定其他结构,它首先将其包装在对象数据类型数组中
pickle
可以直接保存字典,并在内部使用
save
编写数组。实际上,
save
使用
pickle
处理save的字典部分。换句话说,将0d数组转换为1d数组,使用
[(0,)]
索引而不是
[()]
,索引表达式的参数始终是元组,无论
()
是否显式。