如何在Python中读取HDF5文件

问题描述 投票:39回答:7

我试图从Python中读取hdf5文件中的数据。我可以使用h5py读取hdf5文件,但我无法弄清楚如何访问文件中的数据。

我的代码

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

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

python hdf5
7个回答
79
投票

阅读HDF5

import h5py
filename = 'file.hdf5'
f = h5py.File(filename, 'r')

# 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
data_file = h5py.File('file.hdf5', 'w')
data_file.create_dataset('group_name', data=data_matrix)
data_file.close()

有关更多信息,请参阅h5py docs

备择方案

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

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

另见:read & write

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


16
投票

你可以使用熊猫。

write

5
投票

读取文件

Comparison of data serialization formats

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

Configuration files in Python

提取数据

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

1
投票

您需要做的是创建一个数据集。如果您查看快速入门指南,它会向您显示您需要使用文件对象来创建数据集。那么,import h5py f = h5py.File(file_name, mode) 然后你就可以读取数据了。这在for key in f.keys(): print(key) #Names of the groups in HDF5 file. 中有解释。


1
投票

要将.hdf5文件的内容作为数组读取,您可以执行以下操作

#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()

1
投票

使用下面的代码读取数据并转换为numpy数组

f.create_dataset

1
投票

这是我刚写的一个简单的函数,它读取由keras中的save_weights函数生成的.hdf5文件,并返回一个带有图层名称和权重的dict:

docs

> import numpy as np > myarray = np.fromfile('file.hdf5', dtype=float) > print(myarray)

没有彻底测试它,但为我做的工作。

© www.soinside.com 2019 - 2024. All rights reserved.