NumPy Tutorial NumPy Statistics NumPy References

NumPy - subtract() function

The NumPy subtract() function is used to subtract arguments element-wise. The syntax for using this function is given below:

Note: It is equivalent to x1 - x2 in terms of array broadcasting.


numpy.subtract(x1, x2, out=None)


x1, x2 Required. Specify the arrays to be subtracted. 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 difference of x1 and x2, element-wise.


The example below shows the usage of subtract() 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]])

#subtract 5 from each element of Arr1
print("subtract(Arr1, 5) returns:")
print(np.subtract(Arr1, 5))

#subtracting elements of Arr2 from Arr1
#Arr1 and Arr2 are broadcastable
print("\nsubtract(Arr1, Arr2) returns:")
print(np.subtract(Arr1, Arr2))

#subtracting elements of Arr3 from Arr1
#Arr1 and Arr3 are broadcastable
print("\nsubtract(Arr1, Arr3) returns:")
print(np.subtract(Arr1, Arr3))

#subtracting elements of Arr4 from Arr1
print("\nsubtract(Arr1, Arr4) returns:")
print(np.subtract(Arr1, Arr4))

The output of the above code will be:

subtract(Arr1, 5) returns:
[[ 5 15]
 [25 35]]

subtract(Arr1, Arr2) returns:
[[ 8 17]
 [28 37]]

subtract(Arr1, Arr3) returns:
[[ 8 18]
 [27 37]]

subtract(Arr1, Arr4) returns:
[[ 8 17]
 [26 35]]

❮ NumPy - Functions