Sometimes you need to check if two arrays are same or compare their values. NumPy provides multiple ways to do this from simple equality checks to element-wise comparisons. Comparing arrays helps in:
- Validating data correctness
- Checking results of operations
- Filtering or selecting data based on conditions
Let’s explore different methods to compare two arrays.
Using np.array_equal()
The array_equal() function is the simplest and most reliable way to compare two arrays. It checks whether:
- Both arrays have the same shape
- All elements are exactly the same
Syntax:
numpy.array_equal(arr1, arr2)
Example: This code compares two arrays using np.array_equal() and prints whether they are equal.
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[1, 2], [3, 4]])
if np.array_equal(arr1, arr2):
print("Equal")
else:
print("Not Equal")
Output
Equal
Explanation: np.array_equal() returns True if arrays have the same elements and shape. It’s the cleanest and most reliable way to check equality.
Using == and .all()
This method first compares arrays element-wise using ==, then checks if all results are True with .all().
Example: This code uses element-wise comparison followed by .all() to decide if two arrays are fully equal.
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[1, 2], [3, 4]])
dif = arr1 == arr2
b = dif.all()
print(b)
Output
True
Explanation: Every element matches, so result is True. If even one element was different, it would return False.
Using Comparison Operators (>, <, >=, <=)
This method is not for equality checks, but for comparing values element by element. It helps when you want to know which array elements are greater/smaller.
Example: This code compares two arrays element by element using greater/less operators.
import numpy as np
a = np.array([101, 99, 87])
b = np.array([897, 97, 111])
print("Array a:", a)
print("Array b:", b)
print("a > b:", np.greater(a, b))
print("a >= b:", np.greater_equal(a, b))
print("a < b:", np.less(a, b))
print("a <= b:", np.less_equal(a, b))
Output
Array a: [101 99 87] Array b: [897 97 111] a > b: [False True False] a >= b: [False True False] a < b: [ True False True] a <= b: [ True False True]
Explanation: The result is a Boolean array, where each element shows the comparison result at that position. This is useful for conditional checks, not equality.