我试图从Python中读取hdf5文件中的数据。我可以使用h5py
读取hdf5文件,但我无法弄清楚如何访问文件中的数据。
import h5py
import numpy as np
f1 = h5py.File(file_name,'r+')
这有效,文件被读取。但是如何访问文件对象f1
中的数据?
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])
#!/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
你可以使用熊猫。
write
读取文件
Comparison of data serialization formats
通过打印HDF5组存在来研究文件的结构
Configuration files in Python
提取数据
import pandas as pd
pd.read_hdf(filename,key)
您需要做的是创建一个数据集。如果您查看快速入门指南,它会向您显示您需要使用文件对象来创建数据集。那么,import h5py
f = h5py.File(file_name, mode)
然后你就可以读取数据了。这在for key in f.keys():
print(key) #Names of the groups in HDF5 file.
中有解释。
要将.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()
使用下面的代码读取数据并转换为numpy数组
f.create_dataset
这是我刚写的一个简单的函数,它读取由keras中的save_weights函数生成的.hdf5文件,并返回一个带有图层名称和权重的dict:
docs
> import numpy as np
> myarray = np.fromfile('file.hdf5', dtype=float)
> print(myarray)
。
没有彻底测试它,但为我做的工作。