python - 当索引重叠时,numpy 高级索引就地增量的语义是什么?

标签 python numpy

我想使用高级索引来增加 numpy 数组,例如

import numpy
x = numpy.array([0,0])
indices = numpy.array([1,1])
x[indices] += [1,2]
print x #prints [0 2]

我本以为结果是 [0 3],因为 1 和 2 都应该添加到 x 的第二个零,但显然 numpy 只添加与特定索引匹配的最后一个元素。 这是一般行为,我可以依赖它,还是这是未定义的行为,可能会随着 numpy 的不同版本而改变?

此外,是否有一种(简单)方法让 numpy 添加与索引匹配的所有元素,而不仅仅是最后一个元素?

最佳答案

来自 numpy docs :

For advanced assignments, there is in general no guarantee for the iteration order. This means that if an element is set more than once, it is not possible to predict the final result.

您可以使用 np.add.at 来获得所需的行为:

Help on built-in function at in numpy.add:

numpy.add.at = at(...) method of numpy.ufunc instance at(a, indices, b=None)

Performs unbuffered in place operation on operand 'a' for elements
specified by 'indices'. For addition ufunc, this method is equivalent to
`a[indices] += b`, except that results are accumulated for elements that
are indexed more than once. For example, `a[[0,0]] += 1` will only
increment the first element once because of buffering, whereas
`add.at(a, [0,0], 1)` will increment the first element twice.

.. versionadded:: 1.8.0

<截图>

示例:

>>> b = np.ones(2, int)
>>> a = np.zeros(2, int)
>>> c = np.arange(2,4)
>>> np.add.at(a, b, c)
>>> a
array([0, 5])

关于python - 当索引重叠时,numpy 高级索引就地增量的语义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42276431/

相关文章:

python - Plotly:如何使用 plotly express 在单迹散点图中显示图例?

python - 从 Numpy 的 SVD 分解中获得负 S 值?

python - 为什么numpy.core.numeric._typelessdata中有两个np.int64(为什么numpy.int64不是numpy.int64?)

python - 根据数据帧中值的重复创建计数器

python - CMD中的`python`返回"` python ` is not recognized ..."

python - 如何在多变量函数中只调用一个变量?

python - 切片 2d numpy 数组

python - Pandas、scipy 和 numpy 的 MAD 结果不同

python - 只有整数、切片 (`:` )、省略号 (`...` )、numpy.newaxis (`None` ) 和整数或 bool 数组是有效的索引

python查找字符串中重复的子串