Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.array.__iadd__ and repeated indices [duplicate]

Tags:

python

numpy

I have an array:

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

and list of indices with repetitions:

idx = [0, 0, 1, 1, 2, 2]

and another array i would like to add to A using indices above:

B = np.array([1, 1, 1, 1, 1, 1])

The operation:

A[idx] += B

Gives the result: array([1, 1, 1]), so obviously values from B were not summed up. What is the best way to get as a result array([2, 2, 2])? Do I have to iterate over indices?

like image 337
mrkwjc Avatar asked Jun 07 '14 16:06

mrkwjc


People also ask

Can you index a NumPy array?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

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.

How do I assign a NumPy array?

We can assign new values to an element of a NumPy array using the = operator, just like regular python lists. A few examples are below (note that this is all one code block, which means that the element assignments are carried forward from step to step).


1 Answers

for this numpy 1.8 added the at reduction:

at(a, indices, b=None)

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. For example, a[[0,0]] += 1 will only increment the first element once because of buffering, whereas add.at(a, [0,0], 1) will increment the first element twice.

.. versionadded:: 1.8.0

In [1]: A = np.array([0, 0, 0])
In [2]: B = np.array([1, 1, 1, 1, 1, 1])
In [3]: idx = [0, 0, 1, 1, 2, 2]
In [4]: np.add.at(A, idx, B)
In [5]: A
Out[5]: array([2, 2, 2])
like image 142
jtaylor Avatar answered Oct 09 '22 16:10

jtaylor