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

问题描述 投票:0回答:2

我有以下 HDF5 文件,我可以在数据中提取列表 ['model_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']里面

python hdf5 h5py
2个回答
2
投票

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

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

接下来,学习如何遍历数据结构。在 h5py 中,您可以使用

visititems()
方法来完成此操作。我最近写了一个 SO 答案并举了一个例子。请参阅此答案:SO 65793692:visititems() 递归遍历节点的方法

在您的情况下,听起来您只需要读取此路径定义的数据集中的数据:

'[data/model_cints]'
'[data][model_cints]'
。两者都是有效的路径定义。 (
'data'
是一个组,
'model_cints'
是一个数据集。组类似于文件夹/目录,数据集类似于文件。)

一旦有了数据集路径,您就需要获取数据类型(如 NumPy dtype)。您可以使用 h5py 获得此属性(以及形状属性),就像使用 NumPy 一样。这就是我从你的 dtype 中得到的:

[('fs_date', '<f8'), ('date', '<f8'), ('prob', 'i1'), ('ymin', '<f8'), ('ymax', '<f8'), ('type', 'O'), ('name', 'O')]

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

我将所有这些放在下面的代码中。它显示了访问数据的不同方法。 (希望多种方法不会混淆这个解释。)每种方法都有用,具体取决于您想要如何读取数据。

注意:此数据看起来像是多个测试的结果合并到一个文件中。如果您想查询特定的测试值,您应该研究 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)

0
投票

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

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

你想要的是

data = np.array(f['data']['model_cints'])
© www.soinside.com 2019 - 2024. All rights reserved.