【问题标题】:Unable to modify an item in a larger dataset无法修改较大数据集中的项目
【发布时间】:2019-07-16 00:17:34
【问题描述】:

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

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

【问题讨论】:

    标签: python numpy dataset hdf5 h5py


    【解决方案1】:

    问题在于您的索引方式。为了做你想做的事,你需要写信给项目[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
    

    【讨论】:

    • 感谢您的回答。
    猜你喜欢
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    相关资源
    最近更新 更多