Python

Numpy Np.Add.At

The add.at a function in NumPy allows you to perform an in-place operation on the left-side operand.

In the case of an addition operation, the function will add the right operand to the left operand at the specified array index.

The syntax is as illustrated below:

1
a[indicies] += b

In simple terms, the function will take each element in a specified array index and add the right operand to it.

Function Syntax

The function syntax is as shown below:

1
ufunc.at(a, indices, b=None, /)

The parameters are as shown:

  1. a – refers to the input array.
  2. indices – target array index or indicies.
  3. b – refers to the right-hand operand.

Example

The code below shows how to use the add.at function to add one value to each element in an input array:

1
2
3
4
arr = np.array([2,3,4])
# select target indices and add 1
np.add.at(arr, [0,1,2], 1)
print(arr)

In the code above, we start by selecting the target indices as shown [0,1,2]. We then specify the value we wish to add to the arrays.

The code above should return:

1
[3 4 5]

Example #2

You can also perform an in-place subtraction as shown:

1
2
3
4
arr = np.array([2,3,4])
# select target indices and add 1
np.subtract.at(arr, [0,1,2], 1)
print(arr)

This should return:

1
[1 2 3]

Conclusion

This short article discussed the basics of using the ufunc at() function in NumPy.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list