【问题标题】:numpy.array.__iadd__ and repeated indices [duplicate]numpy.array.__iadd__ 和重复索引[重复]
【发布时间】:2014-06-07 16:42:47
【问题描述】:

我有一个数组:

A = np.array([0, 0, 0])

和重复的索引列表:

idx = [0, 0, 1, 1, 2, 2]

以及我想使用上面的索引添加到 A 的另一个数组:

B = np.array([1, 1, 1, 1, 1, 1])

操作:

A[idx] += B

给出结果:array([1, 1, 1]),所以显然来自B 的值没有相加。作为结果array([2, 2, 2]) 的最佳方法是什么?我必须迭代索引吗?

【问题讨论】:

标签: python numpy


【解决方案1】:

为此 numpy 1.8 添加了 at 缩减:

at(a, indices, b=None)

对元素的操作数“a”执行非缓冲原地操作 由“索引”指定。对于添加ufunc,这个方法是等价的 到a[indices] += b,除了为元素累加结果 索引不止一次。例如,a[[0,0]] += 1 将 由于缓冲,只增加第一个元素一次,而 add.at(a, [0,0], 1) 将使第一个元素增加两次。

.. 版本添加:: 1.8.0

In [1]: A = np.array([0, 0, 0])
In [2]: B = np.array([1, 1, 1, 1, 1, 1])
In [3]: idx = [0, 0, 1, 1, 2, 2]
In [4]: np.add.at(A, idx, B)
In [5]: A
Out[5]: array([2, 2, 2])

【讨论】:

  • 就是这样!它似乎比迭代快几倍,并且也适用于多维数组。谢谢。
【解决方案2】:

怎么样:

A = np.array([1, 2, 3])
idx = [0, 0, 1, 1, 2, 2]
A += np.bincount(idx, minlength=len(A))

如果 A 从零开始,显然会更简单:

A = np.bincount(idx)

【讨论】:

    猜你喜欢
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 2021-11-02
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 2012-09-11
    相关资源
    最近更新 更多