NumPy subtract()
Summary: in this tutorial, you’ll learn how to use the numpy subtract()
function or the – operator to find the difference between two equal-sized arrays.
Introduction to the Numpy subtract function
The -
or subtract()
function returns the difference between two equal-sized arrays by performing element-wise subtractions.
Let’s take some examples of using the -
operator and subtract()
function.
Using NumPy subtract() function and – operator to find the difference between two 1D arrays
The following example uses the -
operator to find the difference between two 1-D arrays:
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])
c = b – a
print(c)
Output:
[2 2]
How it works.
First, create two 1D arrays with two numbers in each:
a = np.array([1, 2])
b = np.array([2, 3])
Second, find the difference between the array b and array a by using the -
operator:
c = a - b
The -
operator returns the difference between each element of array b with the corresponding element of array a:
[2-1, 3-2] = [1,1]
Similarly, you can use the subtract()
function to find the difference between two 1D arrays like this:
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])
c = np.subtract(b, a)
print(c)
Output:
[2 2]
Using NumPy subtract function and – operator to find the difference between two 2D arrays example
The following example uses the -
operator to find the difference between two 2D arrays:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = b – a
print(c)
Output:
[[4 4]
[4 4]]
In this example, the -
operator performs element-wise subtraction:
[[ 5-1 6-2]
[7-3 8-4]]
Likewise, you can use the subtract()
function to find the difference between two 2D arrays:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = np.subtract(b, a)
print(c)
Output:
[[4 4]
[4 4]]
Summary
- Use the
-
operator orsubtract()
function to find the difference between two equal-sized arrays.