【发布时间】:2015-06-03 10:03:51
【问题描述】:
我想向数组添加一个常量值。该数组存储在 hdf5 文件中。
f = h5py.File(fileName)
f['numbers'] = f['numbers'] + 5
给我一个TypeError: unsupported operand type(s) for +: 'Dataset' and 'int'的错误
我该怎么做?
【问题讨论】:
标签: python file numpy hdf5 h5py
我想向数组添加一个常量值。该数组存储在 hdf5 文件中。
f = h5py.File(fileName)
f['numbers'] = f['numbers'] + 5
给我一个TypeError: unsupported operand type(s) for +: 'Dataset' and 'int'的错误
我该怎么做?
【问题讨论】:
标签: python file numpy hdf5 h5py
f['numbers'][:]+=5 有效。
f['numbers'] + 5 不起作用,因为 Dataset 对象没有像 __add__ 这样的方法。所以 Python 解释器会给你unsupported 错误。
添加[:] 会得到一个ndarray,以及完整的numpy 方法集。
文档不是说将数据切片加载到内存中吗?
`f['numbers'][:10] += 5
可能会作为更改部分的方式。添加仍在内存中完成。
查看之前的问题,例如 How to store an array in hdf5 file which is too big to load in memory?
另一种选择是查看编译后的h5 代码。可能有基于 Fortran 或 C 的脚本会像这样对数据进行更改。您可以轻松地从 Python 中调用它们。
【讨论】:
你必须使用the actual numpy.add function:
ds = f['numbers']
ds[:] = np.add(ds, 5)
(虽然我确实更喜欢你的语法。也许这值得向 h5py 人建议。)
【讨论】: