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)
Code language: Python (python)

Output:

[2 2]Code language: Python (python)

How it works.

First, create two 1D arrays with two numbers in each:

a = np.array([1, 2])
b = np.array([2, 3])Code language: Python (python)

Second, find the difference between the array b and array a by using the - operator:

c = a - bCode language: Python (python)

The - operator returns the difference between each element of array b with the corresponding element of array a:

[2-1, 3-2] = [1,1]Code language: Python (python)

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)
Code language: Python (python)

Output:

[2 2]Code language: Python (python)

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)
Code language: Python (python)
numpy subtract 2d arrays

Output:

[[4 4]
 [4 4]]Code language: Python (python)

In this example, the - operator performs element-wise subtraction:

[[ 5-1  6-2]
 [7-3 8-4]]Code language: Python (python)

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)Code language: Python (python)

Output:

[[4 4]
 [4 4]]Code language: Python (python)

Summary

  • Use the subtract operator (-) or subtract() function to find the difference between two equal-sized arrays.
Did you find this tutorial helpful ?