Skip to main content
 首页 » 编程设计

python之如何使用 h5py 更新二维数组

2025年05月04日9jillzhang

我想用 hdf5 存储一个二维数组,但无法更新它。

import numpy as np 
import h5py 
 
# create a new storage 
fh = h5py.File('dummy.h5', 'w') 
fh.create_dataset('random', data=np.array([[0, 1], [2, 3]])) 
fh.close() 
 
# try to change the first array cell to value 6 
fh = h5py.File('dummy.h5', 'a') 
fh['random'][0][0] = 6 
fh.close() 
 
# read the array and print out the value at the first position 
fh = h5py.File('dummy.h5', 'r') 
print fh['random'][0][0] # print out '0' not '6' 
fh.close() 

此代码适用于普通的 1 维数组。它如何与 2 dim 阵列一起使用?

请您参考如下方法:

伯恩哈德

这是一个很好的问题。我有一个快速的解决方法,但对 h5py(和 hdf5)的理解太浅,不知道为什么这有效,但你的方法却不起作用。

快速回答/解决方法

按元组索引,即 arr[x,y] 而不是 arr[x][y] 确实有效(第 10 行和11 下面):

In [2]: fh = h5py.File('dummy.h5','a') 
In [6]: fh['random'].value 
Out[6]:  
array([[0, 1], 
       [2, 3]]) 
In [8]: fh['random'][0][0] = 6 
In [9]: fh['random'].value 
Out[9]:  
array([[0, 1], 
       [2, 3]]) 
In [10]: fh['random'][0,0] = 6 
In [11]: fh['random'].value 
Out[11]:  
array([[6, 1], 
       [2, 3]])