我发现了一个不雅的解决方案,我想知道是否有更好的方法来解决这个问题。(使用python 3.6(
我想将一组实验结果存储在.hdf5
文件的不同组中。但我希望能够打开文件,迭代所有组,只从特定类型的组中获取数据集。
我发现的不雅的解决方案是保留组名中用于区分组的信息。例如"ExpA01"
中的01
。
生成文件的代码:
import h5py
import numpy as np
if __name__ == "__main__":
# name of the file
FileName = "myFile.hdf5"
# open the file
myFile = h5py.File(FileName, 'w')
# list of groups
NameList = ["ExpA01", "ExpA02", "ExpB01", "ExpB02"]
for name in NameList:
# create new group with the name from the nameList
myFile.create_group(name)
# create random data
dataset = np.random.randint(0, 10, 10)
# add data set to the group
myFile[name].create_dataset("x", data=dataset)
myFile.close() # close the file
现在我只想读取以"01"
结尾的组中的数据。为此,我基本上从组名myFile[k].name.split("/")[-1][-2::] == "01"
中读取信息。
读取文件的代码:
import h5py
import numpy as np
if __name__ == "__main__":
FileName = "myFile.hdf5"
# open the file
myFile = h5py.File(FileName, 'r')
for k in myFile.keys(): # loop over all groups
if (myFile[k].name.split("/")[-1][-2::] == "01"):
data = np.zeros(myFile[k]["x"].shape)
myFile[k]["x"].read_direct(data)
print(data)
myFile.close()
简而言之,将区分信息写入组名,然后对字符串进行切片是一种糟糕的解决方案。
有什么更好的方法可以做到这一点?
感谢阅读。
您是否考虑过为每个组添加一个属性
然后您可以根据属性值的测试来筛选组。属性数据类型没有限制。我的示例使用字符串,但它们可以是int或float。
# Quick example to create a group attribute, then retrieve:
In [3]: h5f = h5py.File('attr_test.h5','w')
In [4]: grp = h5f.create_group('group1')
In [5]: h5f['group1'].attrs['key']='value'
...:
In [6]: get_value = h5f['group1'].attrs['key']
In [7]: print (get_value)
value
我想我应该添加另一个具有两个不同属性值的示例。它创建了26个名为group_a
到group_z
的组,并将a/e/i/o/u
的key
属性设置为vowel
,将所有其他字母的consonant
属性设置为。
vowels = 'aeiouAEIOU'
h5f = h5py.File('attr_test.h5','w')
for ascii in range(97,123):
grp = h5f.create_group('group_'+chr(ascii))
if chr(ascii) in vowels:
grp.attrs['key']='vowel'
else :
grp.attrs['key']='consonant'
for grp in h5f.keys() :
get_value = h5f[grp].attrs['key']
print (grp,':',get_value)