简体   繁体   English

在另一个ndarray特定位置的ndarray的总和元素(类似于np.put)

[英]Numpy sum elements of ndarray at specific positions of another ndarray (similar to np.put)

I'd like to accumulate the sum of a numpy array at specific positions of another numpy array without using any loop. 我想在不使用任何循环的情况下在另一个numpy数组的特定位置累积numpy数组的总和。 This is similar to what numpy.put does, but I'd like to accumule the sum instead of replacing the elements. 这类似于numpy.put的操作,但是我想累加总和而不是替换元素。

Consider the following example: 考虑以下示例:

import numpy as np
a = np.zeros([2, 2])
b = np.array([[1, 2], [3, 4], [5, 6]])
indices = np.array([[0, 2], [0, 1], [0, 1]])

Here, np.put(a, indices, b) gives the following result: 在这里, np.put(a, indices, b)np.put(a, indices, b)得到以下结果:

a = [[ 5. 6.][ 2. 0.]]

Instead, I'd like to obtain: 相反,我想获得:

a = [[ 9. 10.][ 2. 0.]]

Is there an efficient way to do this? 有一种有效的方法可以做到这一点吗?

You could use np.add.at : 您可以使用np.add.at

>>> import numpy as np
>>> a = np.zeros([2, 2])
>>> b = np.array([[1, 2], [3, 4], [5, 6]])
>>> indices = np.array([[0, 2], [0, 1], [0, 1]])
>>> 
>>> np.add.at(a.ravel(), indices.ravel(), b.ravel())
>>> a
array([[  9.,  10.],
       [  2.,   0.]])
>>> 

an alternative, and in my experience often quite a bit faster is np.bincount : 另一种选择,根据我的经验,通常快得多的是np.bincount

>>> a = np.zeros([2, 2])
>>> a += np.bincount(indices.ravel(), b.ravel(), minlength=a.size).reshape(a.shape)
>>> a
array([[  9.,  10.],
       [  2.,   0.]])
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM