Python 如何使用h5py覆盖h5文件中的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22922584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to overwrite array inside h5 file using h5py
提问by user3508433
I'm trying to overwrite a numpy array that's a small part of a pretty complicated h5 file.
我试图覆盖一个 numpy 数组,它是一个非常复杂的 h5 文件的一小部分。
I'm extracting an array, changing some values, then want to re-insert the array into the h5 file.
我正在提取一个数组,更改一些值,然后想将该数组重新插入到 h5 文件中。
I have no problem extracting the array that's nested.
提取嵌套的数组没有问题。
f1 = h5py.File(file_name,'r')
X1 = f1['meas/frame1/data'].value
f1.close()
My attempted code looks something like this with no success:
我尝试的代码看起来像这样但没有成功:
f1 = h5py.File(file_name,'r+')
dset = f1.create_dataset('meas/frame1/data', data=X1)
f1.close()
As a sanity check, I executed this in Matlab using the following code, and it worked with no problems.
作为完整性检查,我使用以下代码在 Matlab 中执行了此操作,并且没有任何问题。
h5write(file1, '/meas/frame1/data', X1);
Does anyone have any suggestions on how to do this successfully?
有没有人对如何成功地做到这一点有任何建议?
回答by askewchan
You want to assign values, not create a dataset:
您要分配值,而不是创建数据集:
f1 = h5py.File(file_name, 'r+') # open the file
data = f1['meas/frame1/data'] # load the data
data[...] = X1 # assign new values to data
f1.close() # close the file
To confirm the changes were properly made and saved:
要确认更改已正确进行并保存:
f1 = h5py.File(file_name, 'r')
np.allclose(f1['meas/frame1/data'].value, X1)
#True
回答by weatherfrog
askewchan's answerdescribes the way to do it (you cannot create a dataset under a name that already exists, but you can of course modify the dataset's data). Note, however, that the dataset must have the same shape as the data (X1) you are writing to it. If you want to replacethe dataset with some other dataset of different shape, you first have to delete it:
askewchan 的回答描述了这样做的方法(您不能以已经存在的名称创建数据集,但您当然可以修改数据集的数据)。但是请注意,数据集必须与X1您写入的数据 ( )具有相同的形状。如果你想用其他不同形状的数据集替换数据集,你首先必须删除它:
del f1['meas/frame1/data']
dset = f1.create_dataset('meas/frame1/data', data=X1)

