无法修改较大数据集中的项目

Unable to modify an item in a larger dataset

我的数据集由一个多维矩阵数组组成。我正在尝试更改其中一个矩阵的值,但即使在我重新分配新值后,我编写的代码仍显示旧值:

import h5py
import numpy as np

f1 = h5py.File('myfile.h5', 'r+')
print("Keys: %s" % f1.keys())
print("old value is :", f1["myArray"][0][0][0])
f1["myArray"][0][0][0] = 100
f1.close()

f2 = h5py.File('myfile.h5', 'r')
print("Keys: %s" % f2.keys())
print("new value is :", f2["myArray"][0][0][0])
f2.close()

问题在于您如何建立索引。要执行您想要的操作,您需要写入项目 [0,0,0](而不是 [0][0][0])。以下代码可以满足您的预期:

import h5py
import numpy as np

file = h5py.File('myfile.h5', 'w')

file["myArray"] = np.arange(5*5*5).reshape(5,5,5)
print("old value is :", file["myArray"][0,0,0])

file["myArray"][0,0,0] = 100
print("new value is :", file["myArray"][0,0,0])

file.close()

(当您 close/reopen 文件时也有效,为清楚起见我省略了)。此代码输出:

old value is : 0
new value is : 100

请考虑 Numpy's documentation on indexing 以获取更多信息。


阅读文档后,您应该会感到惊讶,您所做的并没有奏效。因为

A = np.arange(5*5*5).reshape(5,5,5)
A[0][0][0] = 100
print(A[0,0,0])

输出 100。这是有效的,因为每次你做 [0] 你都会得到一个指向子数组(而不是副本)的指针。因此,修改此子数组的条目会修改基础数据(原始数组)。

我的猜测是因为 h5py 写入光盘,所以第一次 [0] 做 return 复制 (而此后指针是 returned)。这个怀疑在这个例子中得到证实:

import h5py
import numpy as np

file = h5py.File('myfile.h5', 'w')
file["myArray"] = np.arange(5*5*5).reshape(5,5,5)

data = file["myArray"][0]
data[0,0] = 100
print(data[0,0])
print(file["myArray"][0,0,0])

file.close()

输出

100
0