如何在 Python 中读取 HDF5 文件

新手上路,请多包涵

我正在尝试从 Python 中的 hdf5 文件中读取数据。我可以使用 h5py 读取 hdf5 文件,但我不知道如何访问文件中的数据。

我的代码

import h5py
import numpy as np
f1 = h5py.File(file_name,'r+')

这有效并且文件被读取。但是如何访问文件对象 f1 中的数据?

原文由 Sameer Damir 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.2k
2 个回答

读取 HDF5

 import h5py
filename = "file.hdf5"

with h5py.File(filename, "r") as f:
    # Print all root level object names (aka keys)
    # these can be group or dataset names
    print("Keys: %s" % f.keys())
    # get first object name/key; may or may NOT be a group
    a_group_key = list(f.keys())[0]

    # get the object type for a_group_key: usually group or dataset
    print(type(f[a_group_key]))

    # If a_group_key is a group name,
    # this gets the object names in the group and returns as a list
    data = list(f[a_group_key])

    # If a_group_key is a dataset name,
    # this gets the dataset values and returns as a list
    data = list(f[a_group_key])
    # preferred methods to get dataset values:
    ds_obj = f[a_group_key]      # returns as a h5py dataset object
    ds_arr = f[a_group_key][()]  # returns as a numpy array

写入 HDF5

 import h5py

# Create random data
import numpy as np
data_matrix = np.random.uniform(-1, 1, size=(10, 3))

# Write data to HDF5
with h5py.File("file.hdf5", "w") as data_file:
    data_file.create_dataset("dataset_name", data=data_matrix)

有关更多信息,请参阅 h5py 文档

备择方案

对于您的应用程序,以下内容可能很重要:

  • 其他编程语言的支持
  • 读/写性能
  • 紧凑性(文件大小)

另见: 数据序列化格式的比较

如果您正在寻找一种制作配置文件的方法,您可能需要阅读我的短文 Python 中的配置文件

原文由 Martin Thoma 发布,翻译遵循 CC BY-SA 4.0 许可协议

读取文件

import h5py

f = h5py.File(file_name, mode)

通过打印存在的 HDF5 组来研究文件的结构

for key in f.keys():
    print(key) #Names of the root level object names in HDF5 file - can be groups or datasets.
    print(type(f[key])) # get the object type: usually group or dataset

提取数据

#Get the HDF5 group; key needs to be a group name from above
group = f[key]

#Checkout what keys are inside that group.
for key in group.keys():
    print(key)

# This assumes group[some_key_inside_the_group] is a dataset,
# and returns a np.array:
data = group[some_key_inside_the_group][()]
#Do whatever you want with data

#After you are done
f.close()

原文由 Daksh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题