我有以下代码片段:
import h5py
import numpy
## Data set with shape (5, 5) and numpy array containing column names as string
data = numpy.random.random((5, 5))
column_names = numpy.array(["a", "b", "c", "d", "e"])
## Create file pointer
fp = h5py.File("data_set.HDF5", "w")
## Store data
fp["sub"] = data
## Close file
fp.close()
如何HDF5 file
如附图所示的箭头所示,为中的列添加名称?
诀窍是使用Numpy dtype定义字段/列名称,然后使用它定义记录数组。您还可以混合使用变量类型(例如,是否要在同一行上混合整数,浮点数和字符串)。
修改示例如下:
import h5py
import numpy as np
## Data set with shape (5, 5) and list containing column names as string
data = np.random.rand(5, 5)
col_names = ["a", "b", "c", "d", "e"]
## Create file pointer
with h5py.File("data_set_2.HDF5", "w") as fp :
ds_dt = np.dtype( { 'names':col_names,
'formats':[ (float), (float), (float), (float), (float)] } )
rec_arr = np.rec.array(data,dtype=ds_dt)
## Store data
##fp["sub"] = data
ds1 = fp.create_dataset('sub', data=rec_arr )