Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accumulate an array by index in numpy? [duplicate]

I have an array:

a = np.array([0,0,0,0,0,0])

I want to add some other array into each index of a, while the index can appear more than one times. I want to get the some of each index. I write:

a[np.array([1,2,2,1,3])] += np.array([1,1,1,1,1])

but get a to be:

array([0, 1, 1, 1, 0, 0])

But what I want is to get:

array([0, 2, 2, 1, 0, 0])

How to implement this in numpy without for loop?

like image 805
maple Avatar asked Jun 25 '16 04:06

maple


People also ask

How do you repeat an element in a NumPy array?

NumPy: repeat() function The repeat() function is used to repeat elements of an array. Input array. The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

How do you repeat an array in Python?

In Python, if you want to repeat the elements multiple times in the NumPy array then you can use the numpy. repeat() function. In Python, this method is available in the NumPy module and this function is used to return the numpy array of the repeated items along with axis such as 0 and 1.

Can you index an array?

ndarrays can be indexed using the standard Python x[obj] syntax, where x is the array and obj the selection. There are different kinds of indexing available depending on obj: basic indexing, advanced indexing and field access.


3 Answers

Using pure numpy, AND avoiding a for loop:

np.add.at(a, np.array([1,2,2,1,3]), np.array([1,1,1,1,1]))

Output:

>>> a = np.array([0,0,0,0,0,0])
>>> np.add.at(a, np.array([1,2,2,1,3]), np.array([1,1,1,1,1]))
>>> a
array([0, 2, 2, 1, 0, 0])

Please note, this does in-place substitution. This is what is desired by you, but it may not be desired by future viewers. Hence the note :)

like image 122
oxalorg Avatar answered Oct 14 '22 05:10

oxalorg


You could always just iterate yourself. Something like:

for i in [1,2,2,1,3]:
    a[i] += 1
like image 1
Alex Avatar answered Oct 14 '22 07:10

Alex


I don't know of a clever numpy vectorized way to do this... the best I can come up with is:

>>> indices = np.array([1,2,2,1,3])
>>> values = np.array([1,1,1,1,1])
>>> a = np.array([0,0,0,0,0,0])
>>> for i, ix in enumerate(indices):
...   a[ix] += values[i]
... 
>>> a
array([0, 2, 2, 1, 0, 0])
like image 1
mgilson Avatar answered Oct 14 '22 06:10

mgilson