【问题标题】:HDF5 file to dictionaryHDF5 文件到字典
【发布时间】:2021-12-31 10:32:49
【问题描述】:

我有一个以下格式的 hdf5 文件。 {...} 代表组,有些有子组。 使用以下链接下载文件

https://drive.google.com/file/d/1f6a0XEPGE4aSEKODVbJ1Q9AUw24Bt9_2/view?usp=sharing

{'A': np.array(...), 
 'B':np.array(...), 
 'C':{
      'A': np.array(...),
      'B': {...},
      'C': np.array(...),
      'D': np.array(...)},
 'D':{
      'A': {...},
      'B': {...},
      'C': {...},
      'D': {...}}
}

我正在尝试使用以下代码创建字典,但它的格式不正确。有人可以帮忙吗?

import h5py
import numpy as np
driv
def read_hdf5_file(file):

    for key,val in file.items():
        if type(val) == h5py._hl.dataset.Dataset:
            d[key] = np.array(val)
#             print(key,np.array(val))

        else:
            d[key] = read_hdf5_file(val)
    return d

if __name__=='__main__':
    d = dict()
    file = h5py.File("data.hdf5")
    read_hdf5_file(file)

【问题讨论】:

  • “格式不正确”是什么意思?它是什么格式,应该是什么格式?
  • if type(val) == h5py._hl.dataset.Dataset:一般来说,更喜欢使用isinstanceif isinstance(val, h5py._hl.dataset.Dataset):。如果val 是Dataset 的子类,这也将评估为真,而不是type 的第一个变体。 (当然,除非你不想要子类。)
  • @mkrieger1 输出字典的格式与文件的格式不正确。
  • 我怀疑我需要以不同的方式使用递归
  • 请勿发布代码、数据、错误消息等的图像 - 复制或在问题中键入文本。请保留将图像用于图表或演示渲染错误,这些无法通过文本准确描述的事情。有关更多信息,请参阅元常见问题解答条目Why not upload images of code/errors when asking a question?

标签: python numpy hdf5 h5py


【解决方案1】:

这是一个非常简单的示例,展示了如何使用.visititems() 递归迭代对象树中的所有对象(数据集和组)并返回数据集名称和 h5py 对象的字典(其中名称是完整路径)。不幸的是,.visititems() 表现得像一个生成器;如果有returnyield,它将退出。为此,您必须将.visititems()“包装”在作为您的生成器的函数中。这并不难,只是更多的参与。 (或者使用 PyTables...它有一组很棒的“walk”方法可以做到这一点。)

下面的代码(警告:显示它在做什么很冗长。)

def get_ds_dictionaries(name, node):
  
    fullname = node.name
    if isinstance(node, h5py.Dataset):
    # node is a dataset
        print(f'Dataset: {fullname}; adding to dictionary')
        ds_dict[fullname] = node
        print('ds_dict size', len(ds_dict)) 
    else:
     # node is a group
        print(f'Group: {fullname}; skipping')  
    
with h5py.File('data.hdf5','r') as h5f:
        
    ds_dict = {}  
    print ('**Walking Datasets to get dictionaries**\n')
    h5f.visititems(get_ds_dictionaries)
    print('\nDONE')
    print('ds_dict size', len(ds_dict))

【讨论】:

    猜你喜欢
    • 2023-03-02
    • 2020-09-13
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2018-01-11
    相关资源
    最近更新 更多