【问题标题】:How can I loop over HDF5 groups in Python removing rows according to a mask?如何在 Python 中循环遍历 HDF5 组,根据掩码删除行?
【发布时间】:2018-04-28 00:20:33
【问题描述】:

我有一个 HDF5 文件,其中包含许多不同的组,所有这些组都具有相同的行数。我还有一个布尔掩码,用于保留或删除行。我想遍历 HDF5 文件中的所有组,根据掩码删除行。

递归访问所有组的recommended methodvisit(callable),但我不知道如何将我的掩码传递给可调用对象。

下面是一些代码,希望能展示我想要做什么但不起作用:

def apply_mask(name, *args):
    h5obj[name] = h5obj[name][mask]

with h5py.File(os.path.join(directory, filename), 'r+') as h5obj:
    h5obj.visit(apply_mask, mask)

这会导致错误

TypeError: visit() takes 2 positional arguments but 3 were given

如何将我的掩码数组放入此函数中?

【问题讨论】:

  • 您是否面临与我相同的问题,即您必须保留每组的最后 x 行并且您一直有 1000 个左右的组?

标签: python traversal hdf5 h5py


【解决方案1】:

我最终通过一系列骇人听闻的变通方法实现了这一点。如果有更好的解决方案,我很想知道!

with h5py.File(os.path.join(directory, filename), 'r+') as h5obj:
    # Use the visit callable to append to a list of key names
    h5_keys = []
    h5obj.visit(h5_keys.append)
    # Then loop over those keys and, if they're datasets rather than
    # groups, remove the invalid rows
    for h5_key in h5_keys:
        if isinstance(h5obj[h5_key], h5py.Dataset):
            tmp = np.array(h5obj[h5_key])[mask]
            # There is no way to simply change the dataset because its
            # shape is fixed, causing a broadcast error, so it is
            # necessary to delete and then recreate it.
            del h5obj[h5_key]
            h5obj.create_dataset(h5_key, data=tmp)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-19
    • 2010-09-23
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 2017-11-01
    相关资源
    最近更新 更多