[英]Python's numpy array of doubles to and from a HDF file without unnecessary conversions
我有一個 numpy 雙打數組。 np.array([double1, double2, double3, ... , doublen]) 所有數組的元素在 memory 中都是連續的。 我想使用 HDF 文件作為數據容器(保存/加載)。
保存實現為: hdf.create_dataset(name='data', data=np.array([double1, double2, double3, ... , doublen]))
load 實現為: data = np.array(hdf_group['data'])
如何驗證是否沒有發生不必要的轉換,例如 double 到 string 到 double ?
變量 dtype 在整個過程中保持不變。 您可以通過檢查 dtype 來驗證 go。 下面的代碼演示了行為。 (在加載到 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[:])
Output 從上面:
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.]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.