Python 的 numpy 数组在 HDF 文件之间来回切换,无需不必要的转换



我有一个numpy双精度数组。np.array([double1,double2,double3,…,doublen](所有数组的元素在内存中都是连续的。我想使用HDF文件作为数据容器(保存/加载(。

save实现为:hdf.create_dataset(名称="数据",数据=np.array([double1,double2,double3,…,doublen]((

负载实现为:data=np.array(hdf_group['data'](

如何验证没有发生不必要的转换,如从double到string再到double?

变量dtype在整个过程中保持不变。您可以边检查数据类型边进行验证。下面的代码演示了行为。(在加载到HDF5之前,我创建了变量arr来保存np.doubles数组。(

double1 = np.double(1) 
double2 = np.double(2)
double3 = np.double(3)
doublen = np.double(10)
with h5py.File('SO_70168153.h5','w') as hdf:
arr = np.array([double1, double2, double3, doublen])
print(f"np.array:nShape: {arr.shape}, Dtype: {arr.dtype}")
print(arr[:])
hdf.create_dataset(name='data', data=arr )
print(f"HDF dataset:nShape: {hdf['data'].shape}, Dtype: {hdf['data'].dtype}")
print(hdf['data'][:])
data = hdf['data'][:]
print(f"data array:nShape: {data.shape}, Dtype: {data.dtype}")
print(data[:])

来自上方的输出:

np.array:
Shape: (4,), Dtype: float64
[ 1.  2.  3. 10.]
HDF dataset:
Shape: (4,), Dtype: float64
[ 1.  2.  3. 10.]
data array:
Shape: (4,), Dtype: float64
[ 1.  2.  3. 10.]

最新更新