我想用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 dim数组。它如何与2 dim数组一起使用?
答案 0 :(得分:1)
哈德,
这是一个很好的问题。我有一个快速的解决方法,但对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]])