【问题标题】:Add constant value to an array which is stored in an hdf5 file将常量值添加到存储在 hdf5 文件中的数组中
【发布时间】: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


    【解决方案1】:

    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 中调用它们。

    【讨论】:

      【解决方案2】:

      你必须使用the actual numpy.add function:

      ds = f['numbers']
      ds[:] = np.add(ds, 5)
      

      (虽然我确实更喜欢你的语法。也许这值得向 h5py 人建议。)

      【讨论】:

        猜你喜欢
        • 2019-01-29
        • 2021-03-27
        • 1970-01-01
        • 2015-05-26
        • 1970-01-01
        • 2016-07-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多