Suppose you have the following code
a = np.ones(8)
pos = np.array([1, 3, 5, 3])
a[pos] # returns array([ 1., 1., 1., 1.]), where the 2nd and 4th el are the same
a[pos] +=1
The last instruction returns
array([ 1., 2., 1., 2., 1., 2., 1., 1.])
But I'd like that assignments over same indices to be summed up, so as to obtain
array([ 1., 2., 1., 3., 1., 2., 1., 1.])
Someone has already experienced this same situation?
Fancy indexing is conceptually simple: it means passing an array of indices to access multiple array elements at once. For example, consider the following array: import numpy as np rand = np. random. RandomState(42) x = rand.
Indexing in NumPy is a reasonably fast operation. Anyway, when speed is critical, you can use the, slightly faster, numpy. take and numpy.
Appending to numpy arrays is very inefficient. This is because the interpreter needs to find and assign memory for the entire array at every single step. Depending on the application, there are much better strategies. If you know the length in advance, it is best to pre-allocate the array using a function like np.
Looping over Python arrays, lists, or dictionaries, can be slow. Thus, vectorized operations in Numpy are mapped to highly optimized C code, making them much faster than their standard Python counterparts.
Using np.add.at
Performs unbuffered in place operation on operand
a
for elements specified byindices
. For additionufunc
, this method is equivalent toa[indices] += b
, except that results are accumulated for elements that are indexed more than once.
np.add.at(a, pos, 1)
print(a)
array([ 1., 2., 1., 3., 1., 2., 1., 1.])
Do note that the function works in-place.
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