如何在python中从HDF5提取数据?

2024-10-03 09:07:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的HDF5文件,我可以在数据中提取一个列表['model\u cints'],但是,我不知道如何在列表数据中显示数据

https://drive.google.com/drive/folders/1p0J7X4n7A39lHZpCAvv_cw3u-JUZ4WFU?usp=sharing

我尝试使用此代码使用numpy.array,但收到以下消息:

npa = np.asarray(data, dtype=np.float32)

 
ValueError: could not convert string to float: 'model_cints'


npa = np.asarray(data)

npa
Out[54]: array(['model_cints'], dtype='<U11')

这是代码:import h5py

filename = "example.hdf5"

with h5py.File(filename, "r") as f:
    # List all groups
    print("Keys: %s" % f.keys())
    a_group_key = list(f.keys())[0]

    # Get the data
    data = list(f[a_group_key])

数据在['model_cints'内]


Tags: 数据代码列表datamodelnpdrivekeys
2条回答

如果您是HDF5新手,我建议您采用爬行、行走、运行的方法来理解HDF5数据模型、特定的数据模式以及如何使用各种API(包括h5py和Pytable)。HDF5设计为自描述。换句话说,您可以通过检查找出模式。理解模式是处理数据的关键。在理解模式之前进行编码是非常令人沮丧的

我建议新用户从HDF组的开始使用HDFView。这是一个在GUI中查看数据的实用程序,无需编写代码。而且,当您开始编写代码时,直观地验证您是否正确读取了数据也很有帮助

接下来,学习如何遍历数据结构。在h5py中,可以使用visititems()方法来实现这一点。我最近用一个例子写了一个答案。看到这个答案:SO 65793692: visititems() method to recursively walk nodes

在您的情况下,听起来您只需要读取由以下路径定义的数据集中的数据:'[data/model_cints]''[data][model_cints]'。两者都是有效的路径定义。('data'是一个组,'model_cints'是一个数据集。组类似于文件夹/目录,数据集类似于文件。)

一旦有了数据集路径,就需要获取数据类型(如NumPy dtype)。使用h5py和使用NumPy的方法相同,可以获得该属性(以及形状属性)。这是我从您的数据类型中得到的:
[('fs_date', '<f8'), ('date', '<f8'), ('prob', 'i1'), ('ymin', '<f8'), ('ymax', '<f8'), ('type', 'O'), ('name', 'O')]

您拥有的是一个混合类型的数组:4个浮点、1个int和2个字符串。这被提取为NumPy记录数组。这与所有元素都是相同类型(所有int、float或string)的典型数据数组不同。您可以使用行索引(整数)和字段名(尽管也可以使用列索引)访问

我在下面的代码中把所有这些放在一起。它显示了访问数据的不同方法。(希望多个方法不会混淆这一解释。)根据您希望如何读取数据,每个方法都很有用

注意:此数据看起来像是合并到单个文件中的多个测试的结果。如果您可能希望查询以获取特定的测试值,则应调查PyTables。它具有h5py中不可用的一些强大搜索功能,可简化该任务。祝您好运

with h5py.File("example.hdf5", "r") as h5f:
    # Get a h5py dataset object
    data_ds = h5f['data']['model_cints']
    print ('data_ds dtype:', data_ds.dtype, '\nshape:', data_ds.shape)

    # get an array with all fs_date data only
    fs_date_arr = data_ds[:]['fs_date'] 
    print ('fs_date_arr dtype:', fs_date_arr .dtype, '\nshape:', fs_date_arr .shape)

    # Get the entire dataset as 1 numpy record array 
    data_arr_all = h5f['data']['model_cints'][:]
    # this also works:
    data_arr_all = data_ds[:]
    print ('data_arr_all dtype:', data_arr_all.dtype, '\nshape:', data_arr_all.shape)

    # Get the first 6 rows as 1 numpy record array 
    data_arr6 = h5f['data']['model_cints'][0:6][:]
    # this also works:
    data_arr6  = data_ds[0:6][:]
    print ('data_arr6 dtype:', data_arr6.dtype, '\nshape:', data_arr6.shape)

f['data']是一个Group对象,这意味着它有键。当你用它做一个iterable,例如,list(f['data']),或者你迭代它,for something in f['data']:,你会得到它的键,它有一个键。这就解释了

>>> np.array(f['data'])
array(['model_cints'], dtype='<U11')

你想要的是

data = np.array(f['data']['model_cints'])

相关问题 更多 >