Archive d’étiquettes pour : NpAddAt


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:

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:

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:

Conclusion

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



Source link