Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy Advanced Indexing: same index used multiple times in += [duplicate]

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?

like image 410
diningphil Avatar asked Sep 08 '17 10:09

diningphil


People also ask

What is fancy indexing in Python?

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.

Is NumPy indexing fast?

Indexing in NumPy is a reasonably fast operation. Anyway, when speed is critical, you can use the, slightly faster, numpy. take and numpy.

Is appending to NumPy array efficient?

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.

Why NumPy array operations are faster than looping?

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.


1 Answers

Using np.add.at

Performs unbuffered in place operation on operand a for elements specified by indices. For addition ufunc, this method is equivalent to a[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.

like image 134
cs95 Avatar answered Oct 18 '22 21:10

cs95