numpy.array .__ iadd__和重复索引 [英] numpy.array.__iadd__ and repeated indices
问题描述
我有一个数组:
A = np.array([0, 0, 0])
以及具有重复索引的列表:
and list of indices with repetitions:
idx = [0, 0, 1, 1, 2, 2]
和另一个我想使用上面的索引添加到A的数组:
and another array i would like to add to A using indices above:
B = np.array([1, 1, 1, 1, 1, 1])
操作:
A[idx] += B
给出结果:array([1, 1, 1])
,因此显然没有对B
中的值求和.结果array([2, 2, 2])
的最佳获取方式是什么?我必须遍历索引吗?
Gives the result: array([1, 1, 1])
, so obviously values from B
were not summed up. What is the best way to get as a result array([2, 2, 2])
? Do I have to iterate over indices?
推荐答案
为此numpy 1.8添加了at
简化:
for this numpy 1.8 added the at
reduction:
at(a,index,b = None)
at(a, indices, b=None)
对元素的操作数'a'执行无缓冲的就地操作
由索引"指定.对于加法ufunc,此方法等效
到a[indices] += b
,不同之处在于元素的结果是累积的
被多次索引的索引.例如,a[[0,0]] += 1
将
由于缓冲,仅将第一个元素递增一次,而
add.at(a, [0,0], 1)
将第一个元素增加两次.
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.
..版本添加:: 1.8.0
.. versionadded:: 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])
这篇关于numpy.array .__ iadd__和重复索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!