<p>HDF5有一个简单的对象模型,用于存储<a href="https://support.hdfgroup.org/HDF5/doc/RM/RM_H5D.html" rel="nofollow noreferrer">datasets</a>(粗略地说,相当于一个“文件数组”)并将它们组织成组(考虑目录)。在这两种对象类型之上,还有更强大的特性,需要理解层。</p>
<p>手边的是一个“<a href="https://support.hdfgroup.org/HDF5/doc/RM/RM_H5R.html" rel="nofollow noreferrer">Reference</a>”。它是HDF5存储模型中的一个内部地址。</p>
<p>h5py将为您完成所有的工作,而不需要调用任何模糊的例程,因为它试图尽可能多地遵循类似dict的接口(但对于引用,使其透明会更复杂一些)。</p>
<p>在文档中查找的位置是<a href="http://docs.h5py.org/en/latest/refs.html" rel="nofollow noreferrer">Object and Region References</a>。它声明要访问通过引用指向的对象<code>ref</code>,您需要</p>
<pre><code> my_object = my_file[ref]
</code></pre>
<p>在你的问题中,有两个步骤:
一。获取参考
2。获取数据集</p>
<pre><code># Open the file
hf = h5py.File('path/to/file', 'r')
# Obtain the dataset of references
n1 = hf['dataset_name']
# Obtain the dataset pointed to by the first reference
ds = hf[n1[0]]
# Obtain the data in ds
data = ds[:]
</code></pre>
<p>例如,如果包含引用的数据集是二维的,则必须使用</p>
<pre><code>ds = hf[n1[0,0]]
</code></pre>
<p>如果数据集是标量,则必须使用</p>
<pre><code>data = ds[()]
</code></pre>
<p>要同时获取所有数据集,请执行以下操作:</p>
<pre><code>all_data = [hf[ref] for ref in n1[:]]
</code></pre>
<p>假设n1为1D数据集。对于2D来说,这个想法是可行的,但我认为没有捷径可以写出来。</p>
<p>为了全面了解如何使用引用来回访问数据,我编写了一个简短的“writer程序”和一个简短的“reader程序”:</p>
<pre><code>import numpy as np
import h5py
# Open file
myfile = h5py.File('myfile.hdf5', 'w')
# Create dataset
ds_0 = myfile.create_dataset('dataset_0', data=np.arange(10))
ds_1 = myfile.create_dataset('dataset_1', data=9-np.arange(10))
# Create a data
ref_dtype = h5py.special_dtype(ref=h5py.Reference)
ds_refs = myfile.create_dataset('ref_to_dataset', shape=(2,), dtype=ref_dtype)
ds_refs[0] = ds_0.ref
ds_refs[1] = ds_1.ref
myfile.close()
</code></pre>
<p>以及</p>
<pre><code>import numpy as np
import h5py
# Open file
myfile = h5py.File('myfile.hdf5', 'r')
# Read the references
ref_to_ds_0 = myfile['ref_to_dataset'][0]
ref_to_ds_1 = myfile['ref_to_dataset'][1]
# Read the dataset
ds_0 = myfile[ref_to_ds_0]
ds_1 = myfile[ref_to_ds_1]
# Read the value in the dataset
data_0 = ds_0[:]
data_1 = ds_1[:]
myfile.close()
print(data_0)
print(data_1)
</code></pre>
<p>您将注意到,对于引用数据集,不能使用标准的、方便的、类似NumPy的语法。这是因为HDF5引用不能用NumPy数据类型表示。必须一次读一本,一本写一本。</p>