如何使用 `h5py` 调整 HDF5 数组大小

14 投票
2 回答
15778 浏览
提问于 2025-04-18 02:15

我该如何使用 h5py 这个Python库来改变HDF5数组的大小呢?

我试过用 .resize 方法,并且在一个设置了 chunksTrue 的数组上进行操作。可惜的是,我还是缺少了一些东西。

In [1]: import h5py

In [2]: f = h5py.File('foo.hdf5', 'w')

In [3]: d = f.create_dataset('data', (3, 3), dtype='i8', chunks=True)

In [4]: d.resize((6, 3))
/home/mrocklin/Software/anaconda/lib/python2.7/site-packages/h5py/_hl/dataset.pyc in resize(self, size, axis)
--> 277         self.id.set_extent(size)
ValueError: unable to set extend dataset (Dataset: Unable to initialize object)

In [11]: h5py.__version__ 
Out[11]: '2.2.1'

2 个回答

4

你需要把这一行改成:

d = f.create_dataset('data', (3, 3), dtype='i8', chunks=True)

改成:

d = f.create_dataset('data', (3, 3), maxshape=(?, ?), dtype='i8', chunks=True) 

d.resize((?, ?))

?改成你想要的大小(你也可以设置为None

可以在这里查看详细信息: http://docs.h5py.org/en/latest/high/dataset.html#resizable-datasets

16

正如Oren提到的,如果你想以后改变数组的大小,在创建dataset的时候需要使用maxshape。把某个维度设置为None,就可以在以后把这个维度的大小调整到最多2的64次方(这是h5的限制):

In [1]: import h5py

In [2]: f = h5py.File('foo.hdf5', 'w')

In [3]: d = f.create_dataset('data', (3, 3), maxshape=(None, 3), dtype='i8', chunks=True)

In [4]: d.resize((6, 3))

In [5]: h5py.__version__
Out[5]: '2.2.1'

更多信息请查看文档

撰写回答