如何在Python中读取HDF5文件

2024-05-14 19:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的代码

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

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


Tags: 文件数据对象代码nameimportnumpyas
3条回答

读取HDF5

import h5py
filename = 'file.hdf5'

with h5py.File(filename, 'r') as f:
    # List all groups
    print("Keys: %s" % f.keys())
    a_group_key = list(f.keys())[0]

    # Get the data
    data = list(f[a_group_key])

写入HDF5

#!/usr/bin/env python
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('group_name', data=data_matrix)

有关详细信息,请参见h5py docs

替代品

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

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

另请参见:Comparison of data serialization formats

如果您正在寻找创建配置文件的方法,那么您可能需要阅读我的短文Configuration files in Python

你可以用熊猫。

import pandas as pd
pd.read_hdf(filename,key)

读取文件

import h5py

f = h5py.File(file_name, mode)

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

for key in f.keys():
    print(key) #Names of the groups in HDF5 file.

提取数据

#Get the HDF5 group
group = f[key]

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

data = group[some_key_inside_the_group].value
#Do whatever you want with data

#After you are done
f.close()

相关问题 更多 >

    热门问题