Index-based addition with multiplicity in numpy

Question:

Suppose I have a numpy array

nparr = np.array([10,20,30,40,50])

The output of the operation nparr[[1,3,3,4]] += 1 on this array is:

array([10, 21, 30, 41, 51])

Even though the index ‘3’ appears twice. Is there any operation that would let me add with multiplicity, so that the result becomes array([10, 21, 30, 42, 51])?

Asked By: chae

||

Answers:

You can use the np.add.at method to add elements to a NumPy array with multiplicity.

import numpy as np

# Create a NumPy array
nparr = np.array([10, 20, 30, 40, 50])

# Use np.add.at to add elements to the array with multiplicity
np.add.at(nparr, [1, 3, 3, 4], [1, 1, 1, 1])

# Print the updated array
print(nparr)

In this code, the np.add.at method is used to add 1 to the elements at indices 1, 3, and 4 in the array nparr, and to add 2 to the element at index 3 in the array (since the index appears twice in the list of indices). The output of this code is:

array([10, 21, 30, 42, 51])

As you can see, the values were added to the array with multiplicity, so that the element at index 3 was incremented by 2 instead of 1.

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.