当索引重叠时,numpy高级索引就地增量的含义是什么? [英] What are the semantics of numpy advanced indexing in-place increments when the indices overlap?

查看:82
本文介绍了当索引重叠时,numpy高级索引就地增量的含义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to increment a numpy array using advanced indexing, e.g.

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更改?

I would have expected, that the result is [0 3], since both 1 and 2 should be added to the second zero of x, but apparently numpy only adds the last element which matches to a particular index. Is this the general behaviour and I can rely on that, or is this undefined behaviour and could change with a different version of numpy?

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

Additionally, is there an (easy) way to get numpy to add all elements which match the index and not just the last one?

推荐答案

来自numpy

对于高级分配,通常不保证迭代顺序.这意味着,如果一个元素被多次设置,则不可能预测最终结果.

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获得所需的行为:

You can use np.add.at to get the desired behaviour:

有关numpy.add中内置函数的帮助:

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

numpy.add.at = at(...)方法 at(a,index,b = None)

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])

这篇关于当索引重叠时,numpy高级索引就地增量的含义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆