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

标签 python numpy dataset hdf5 h5py

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

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()

(当您关闭/重新打开文件时也可以工作,为了清楚起见,我省略了该文件)。此代码输出:

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] 确实返回了一个副本(而此后返回一个指针)。这个怀疑在这个例子中得到了证实:

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

关于python - 无法修改较大数据集中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54818009/

相关文章:

python - 使用枚举函数,有没有办法在不引用元素的情况下引用索引?

python - 在Python中从字母数字数组中提取一行

math - Scipy arpack eigs 与特征值的 eigsh 数

python - 如何从 (1000, 1) 和索引槽 n 值创建 (1000, 500) 数组?

mysql - 寻找数据集来测试 FULLTEXT 样式搜索

python - Python 中的变量范围问题

python tesseract 结果在句子之间给出了不必要的额外行间隙

Python Api C 产生内存泄漏

winforms - 我们如何解决所有这些 "Conversion from type DBNull to type String is not valid"的问题?

java - 以正确的形式在 JSON 文件中写入数据 JAVA