【问题标题】:How extract data from HDF5 in python?如何在 python 中从 HDF5 中提取数据?
【发布时间】:2021-04-28 03:16:03
【问题描述】:

我有以下 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


    【解决方案1】:

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

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

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

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

    一旦有了数据集路径,就需要获取数据类型(如 NumPy dtype)。你可以像使用 NumPy 一样使用 h5py 获得这个(和 shape 属性)。这是我为您的 dtype 得到的:
    [('fs_date', '&lt;f8'), ('date', '&lt;f8'), ('prob', 'i1'), ('ymin', '&lt;f8'), ('ymax', '&lt;f8'), ('type', 'O'), ('name', 'O')]

    您拥有的是一个混合类型的数组:4 个浮点数、1 个整数和 2 个字符串。这被提取为 NumPy 记录数组。这与所有元素都是相同类型(所有整数、浮点数或字符串)的典型 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)
    

    【讨论】:

      【解决方案2】:

      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'])
      

      【讨论】:

      • 我相信h5py 文档推荐data = f['data'][model_cints'][:] 作为将数据集下载为数组的方式。 np.arraynp.asarray 但建议使用 [:]
      • @hpaulj 似乎确实如此。我还读到了Dataset.read_direct()
      猜你喜欢
      • 2020-06-21
      • 2021-03-23
      • 2020-08-13
      • 2023-01-07
      • 2014-11-07
      • 2015-03-26
      • 2021-10-11
      • 2021-12-09
      • 2022-01-15
      相关资源
      最近更新 更多