简体   繁体   中英

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. This is similar to what numpy.put does, but I'd like to accumule the sum instead of replacing the elements.

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:

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 :

>>> 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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