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?
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.
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.
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.
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 :)
You could always just iterate yourself. Something like:
for i in [1,2,2,1,3]:
a[i] += 1
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With