6

I am trying to efficiently update some elements of a numpy array A, using another array b to indicate the indexes of the elements of A to be updated. However b can contain duplicates which are ignored whereas I would like to be taken into account. I would like to avoid for looping b. To illustrate it:

>>> A = np.arange(10).reshape(2,5)
>>> A[0, np.array([1,1,1,2])] += 1
>>> A
array([[0, 2, 3, 3, 4],
       [5, 6, 7, 8, 9]])

whereas I would like the output to be:

array([[0, 3, 3, 3, 4],
       [5, 6, 7, 8, 9]])

Any ideas?

1
  • In your index array, column index 1 occurs 3 times. If you want the elements to be incremented as many times as the index occurs, then element [0,1] should become 1 + 3 = 4. Commented Mar 11, 2016 at 13:05

2 Answers 2

11

To correctly handle the duplicate indices, you'll need to use np.add.at instead of +=. Therefore to update the first row of A, the simplest way would probably be to do the following:

>>> np.add.at(A[0], [1,1,1,2], 1)
>>> A
array([[0, 4, 3, 3, 4],
       [5, 6, 7, 8, 9]])

The documents for the ufunc.at method can be found here.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. It works as expected. Thank you for the pointer, I didn't know this feature, it is very useful.
0

One approach is to use numpy.histogram to find out how many values there are at each index, then add the result to A:

A[0, :] += np.histogram(np.array([1,1,1,2]), bins=np.arange(A.shape[1]+1))[0]

1 Comment

Thanks for the answer, but I think the accepted one is more intuitive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.