How to Compare Two NumPy Arrays (With Examples)


You can use the following methods to compare the values of two NumPy arrays:

Method 1: Test if Two NumPy Arrays are Element-wise Equal

#test if array A and array B are element-wise equal
np.array_equal(A,B)

Method 2: Test if Two NumPy Arrays are Element-wise Equal (Within a tolerance)

#test if array A and array B are element-wise equal (within absolute tolerance of 2)
np.allclose(A, B, atol=2)

The following examples show how to use each method in practice.

Example 1: Test if Two NumPy Arrays are Element-wise Equal

The following code shows how to use the array_equal() function to test if two NumPy arrays are element-wise equal:

import numpy as np

#create two NumPy arrays
A = np.array([1, 4, 5, 7, 10])
B = np.array([1, 4, 5, 7, 10])

#test if arrays are element-wise equal
np.array_equal(A,B)

True

The function returns True since the two NumPy arrays have the same length with the same values in the same positions.

However, the function will return False if the two NumPy arrays have the same values but in different positions:

import numpy as np

#create two NumPy arrays with same values but in different positions
A = np.array([1, 4, 5, 7, 10])
B = np.array([1, 4, 7, 5, 10])

#test if arrays are element-wise equal
np.array_equal(A,B)

False

Example 2: Test if Two NumPy Arrays are Element-wise Equal (Within Tolerance)

The following code shows how to use the allclose() function to test if two NumPy arrays are element-wise equal within a tolerance value of 2:

import numpy as np

#create two NumPy arrays
A = np.array([1, 4, 5, 7, 10])
B = np.array([1, 4, 7, 8, 10])

#test if arrays are element-wise equal (within absolute tolerance of 2)
np.allclose(A, B, atol=2)

True

The function returns True since the corresponding elements between each NumPy array are all within 2 of each other.

For example, we see that elements in the third and fourth positions of each array are different, but since each pair is within 2 values of each other, the function returns true.

However, if we change the absolute tolerance (atol) argument to 1, then the function will return False:

import numpy as np

#create two NumPy arrays
A = np.array([1, 4, 5, 7, 10])
B = np.array([1, 4, 7, 8, 10])

#test if arrays are element-wise equal (within absolute tolerance of 1)
np.allclose(A, B, atol=1)

False

The function returns False since the corresponding elements in the third position of each NumPy array are not within 1 of each other.

Note: Refer to the NumPy documentation to find a complete explanation of the array_equal and allclose functions.

Additional Resources

The following tutorials explain how to perform other common tasks in NumPy:

How to Shift Elements in NumPy Array
How to Count Occurrences of Elements in NumPy
How to Calculate the Mode of NumPy Array

Leave a Reply

Your email address will not be published.