NumPy - add() function
The NumPy add() function is used to add arguments element-wise. The syntax for using this function is given below:
Note: It is equivalent to x1 + x2 in terms of array broadcasting.
Syntax
numpy.add(x1, x2, out=None)
Parameters
x1, x2 |
Required. Specify the arrays to be added. If x1.shape != x2.shape, they must be broadcastable to a common shape. |
out |
Optional. Specify a location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. |
Return Value
Returns sum of x1 and x2, element-wise.
Example:
The example below shows the usage of add() function.
import numpy as np Arr1 = np.array([[10,20],[30,40]]) Arr2 = np.array([[2,3]]) Arr3 = np.array([[2],[3]]) Arr4 = np.array([[2,3],[4,5]]) #add 5 to each element of Arr1 print("add(Arr1, 5) returns:") print(np.add(Arr1, 5)) #add elements of Arr1 and Arr2 #Arr1 and Arr2 are broadcastable print("\nadd(Arr1, Arr2) returns:") print(np.add(Arr1, Arr2)) #add elements of Arr1 and Arr3 #Arr1 and Arr3 are broadcastable print("\nadd(Arr1, Arr3) returns:") print(np.add(Arr1, Arr3)) #add elements of Arr1 and Arr4 print("\nadd(Arr1, Arr4) returns:") print(np.add(Arr1, Arr4))
The output of the above code will be:
add(Arr1, 5) returns: [[15 25] [35 45]] add(Arr1, Arr2) returns: [[12 23] [32 43]] add(Arr1, Arr3) returns: [[12 22] [33 43]] add(Arr1, Arr4) returns: [[12 23] [34 45]]
❮ NumPy - Functions