【问题标题】:How to read HDF5 attributes (metadata) with Python and h5py如何使用 Python 和 h5py 读取 HDF5 属性(元数据)
【发布时间】:2021-05-14 17:23:16
【问题描述】:

我有一个 HDF5 文件,里面有多个文件夹。每个文件夹都添加了属性(一些调用属性“元数据”)。我知道如何访问文件夹内的密钥,但我不知道如何使用 Python 的 h5py 包提取属性。 以下是来自 HDFView 的属性:

Folder1(800,4)
   Group size = 9
   Number of attributes = 1
        measRelTime_seconds = 201.73

我需要提取这个measRelTime_seconds 值。我已经有一个循环来读取文件

f = h5py.File(file,'r')
        for k,key in enumerate(f.keys()): #loop over folders
            #need to obtain measRelTime_seconds here, I guess

谢谢

【问题讨论】:

  • metadata 是什么意思? h5py 可以读取可能附加到文件、组或数据集的.attr
  • 在查看器上打开文件时有两个选项卡:日志信息和元数据。我也不能使用 .attrs 。我试过f.attrs,但它只返回<Attributes of HDF5 object at 140490175897088>。能告诉我怎么用吗?

标签: python python-3.x metadata hdf5 h5py


【解决方案1】:

属性就像组和数据集一样工作。使用object.attrs.keys() 迭代属性名称。对象可以是文件、组或数据集。

这是一个简单的示例,它在 3 个不同的对象上创建 2 个属性,然后读取并打印它们。

arr = np.random.randn(1000)

with h5py.File('groups.hdf5', 'w') as f:
    g = f.create_group('Base_Group')
    d = g.create_dataset('default', data=arr)

    f.attrs['User'] = 'Me'
    f.attrs['OS'] = 'Windows'

    g.attrs['Date'] = 'today'
    g.attrs['Time'] = 'now'

    d.attrs['attr1'] = 1.0
    d.attrs['attr2'] = 22.2
    
    for k in f.attrs.keys():
        print('{} => {}'.format(k, f.attrs[k]))
    for k in g.attrs.keys():
        print('{} => {}'.format(k, g.attrs[k]))
    for k in d.attrs.keys():
        print('{} => {}'.format(k, d.attrs[k]))

【讨论】:

    【解决方案2】:

    好的,我找到答案了。阅读它你可以简单地检查属性的名称为

    f['Folder'].attrs.keys()
    

    并且可以使用返回值

    f['Folder'].attrs['<name of the attribute>']
    

    【讨论】:

      猜你喜欢
      • 2016-06-05
      • 2016-04-08
      • 2014-06-26
      • 2020-08-13
      • 2020-05-27
      • 2020-11-23
      • 2015-04-17
      • 2016-03-23
      • 1970-01-01
      相关资源
      最近更新 更多