我想使用高级索引来增加 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/