你能在pycharm中查看hdf5文件吗?

时间:2018-05-01 13:37:57

标签: python pycharm hdf5

是否有方法/插件可以在pycharm中查看hdf5文件,这样您就不必安装HDFVIEW来手动检查文件了?

1 个答案:

答案 0 :(得分:2)

您可以使用h5py库。

您可能事先不知道HDF5文件的结构。在这种情况下,您可以使用一个函数来迭代HDF5文件中的所有路径。这是一个示例:

def traverse_datasets(hdf_file):

    """Traverse all datasets across all groups in HDF5 file."""

    import h5py

    def h5py_dataset_iterator(g, prefix=''):
        for key in g.keys():
            item = g[key]
            path = '{}/{}'.format(prefix, key)
            if isinstance(item, h5py.Dataset): # test for dataset
                yield (path, item)
            elif isinstance(item, h5py.Group): # test for group (go down)
                yield from h5py_dataset_iterator(item, path)

    with h5py.File(hdf_file, 'r') as f:
        for (path, dset) in h5py_dataset_iterator(f):
            print(path, dset)

    return None

用法示例:

traverse_datasets('file.h5')

/DataSet1 <HDF5 dataset "DataSet1": shape (655559, 260), type "<f4">
/DataSet2 <HDF5 dataset "DataSet2": shape (22076, 10000), type "<f4">
/index <HDF5 dataset "index": shape (677635,), type "|V384">

然后要读取特定的数据集,可以选择一个路径:

with h5pyFile('file.h5', 'r') as f:
    arr = f['/DataSet1'][:]  # read entire dataset into memory

如果无法将数据保存在内存中,则可以迭代打印或将切片提取到内存中。 h5py documentation有许多示例。语法遵循NumPy约定。