【问题标题】:How can I update arrays in h5py?如何更新 h5py 中的数组?
【发布时间】:2015-06-05 16:04:19
【问题描述】:

我需要一个数组来保存值,但我还想在以后随时编辑数组中的一些值。

我创建了一个包含一些随机值的数组并将其保存到磁盘。我可以阅读它。我想更新它,一个值为“23”的数组切片。当我再次阅读时,它看起来并没有改变。

如何更新这些值?

import numpy as np
import h5py

x, y = 100,20

# create
a = np.random.random(size=(x, y))
h5f = h5py.File('data.h5', 'w')
h5f.create_dataset('dataset_1', data=a)
print a[1][0:5] # [ 0.77474947  0.3618912   0.16000164  0.47827977  0.93955235]
h5f.close()

# read
h5f = h5py.File('data.h5','r')
b = h5f['dataset_1'][:]
print b[1][0:5] #[ 0.77474947  0.3618912   0.16000164  0.47827977  0.93955235]
h5f.close()

# update
h5f = h5py.File('data.h5', 'r+')
b = h5f['dataset_1'][:]
b[1][0:5] = 23
print b[1][0:5] #[ 23.  23.  23.  23.  23.]
h5f.close()

# read again
h5f = h5py.File('data.h5','r')
b = h5f['dataset_1'][:]
print b[1][0:5] #[ 0.77474947  0.3618912   0.16000164  0.47827977  0.93955235]
h5f.close()

【问题讨论】:

    标签: python arrays numpy h5py


    【解决方案1】:

    附加模式适合我。创建文件:

    fh = h5py.File('dummy.h5', 'w')
    fh.create_dataset('random', data=np.reshape(np.asarray([0, 1, 2, 3]), (2, 2)))
    fh.close()
    

    以附加模式打开和编辑('a',默认模式)..

    fh = h5py.File('dummy.h5', 'a')
    print fh['random'][:]
    fh['random'][0, 0] = 1337
    print fh['random'][:]
    fh.close()
    

    ..再检查一遍

    fh = h5py.File('dummy.h5', 'r')
    print fh['random'][:]
    fh.close()
    

    写入模式 ('w') 似乎清除了整个文件。编辑:直接访问数据集很重要。正如之前的回答所指出的:在您的问题描述中,您将“dataset_1”的内容分配给 b,然后编辑 b。

    编辑 1:'r+' 对我也有效,问题可能出在其他地方。也许您访问数据集的方式(按索引而不是按名称)会有所不同。

    编辑 2:也适用于二维。添加了一些关于索引的信息

    【讨论】:

    • 你能用二维数组试试这个吗?像 [[1,2],[3,4]]。您的示例有效,但我仍然没有使用 2 dim 数组保存更新
    • 维度不应该有所作为。我编辑了答案。
    猜你喜欢
    • 2013-04-19
    • 2014-04-09
    • 2014-05-20
    • 2018-03-06
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 2014-02-26
    相关资源
    最近更新 更多