如何在Python中读取HDF5文件
我正在尝试从Python中的hdf5文件读取数据。 我可以使用f1读取hdf5文件,但无法弄清楚如何访问文件中的数据。
我的密码
import h5py
import numpy as np
f1 = h5py.File(file_name,'r+')
这可以正常工作并读取文件。 但是如何访问文件对象f1中的数据?
Sameer Damir asked 2019-11-05T22:33:05Z
8个解决方案
88 votes
读取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。
备择方案
JSON:非常适合编写人类可读的数据; 非常常用(读和写)
CSV:超级简单的格式(读和写)
pickle:Python序列化格式(读和写)
MessagePack(Python软件包):更紧凑的表示形式(读和写)
HDF5(Python软件包):适用于矩阵(读和写)
XML:太*叹*(读和写)
对于您的应用程序,以下内容可能很重要:
其他编程语言的支持
阅读/写作表现
紧凑度(文件大小)
另请参阅:数据序列化格式的比较
如果您想寻找一种制作配置文件的方法,则可能需要阅读我的短文《 Python中的配置文件》。
Martin Thoma answered 2019-11-05T22:34:51Z
18 votes
您可以使用熊猫。
import pandas as pd
pd.read_hdf(filename,key)
Danny answered 2019-11-05T22:35:14Z
8 votes
读取文件
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()
Daksh answered 2019-11-05T22:35:50Z
2 votes
要将.hdf5文件的内容作为数组读取,可以执行以下操作
> import numpy as np
> myarray = np.fromfile('file.hdf5', dtype=float)
> print(myarray)
Raza answered 2019-11-05T22:36:13Z
2 votes
使用以下代码读取数据并将其转换为numpy数组
import h5py
f1 = h5py.File('data_1.h5', 'r')
list(f1.keys())
X1 = f1['x']
y1=f1['y']
df1= np.array(X1.value)
dfy1= np.array(y1.value)
print (df1.shape)
print (dfy1.shape)
ashish bansal answered 2019-11-05T22:36:37Z
2 votes
这是我刚刚编写的一个简单函数,它读取由keras中的save_weights函数生成的.hdf5文件,并返回包含图层名称和权重的字典:
def read_hdf5(path):
weights = {}
keys = []
with h5py.File(path, 'r') as f: # open file
f.visit(keys.append) # append all keys to list
for key in keys:
if ':' in key: # contains data if ':' in key
print(f[key].name)
weights[f[key].name] = f[key].value
return weights
[https://gist.github.com/Attila94/fb917e03b04035f3737cc8860d9e9f9b。]
尚未进行全面测试,但可以为我完成工作。
Attila answered 2019-11-05T22:37:14Z
1 votes
您需要做的是创建一个数据集。 如果您查看快速入门指南,它将显示您需要使用文件对象来创建数据集。 因此,请输入f.create_dataset,然后即可读取数据。 这在文档中进行了解释。
Games Brainiac answered 2019-11-05T22:37:38Z
0 votes
from keras.models import load_model
h= load_model('FILE_NAME.h5')
Judice answered 2019-11-05T22:37:55Z