![]() |
VOOZH | about |
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:
Let’s explore different methods to compare two arrays.
The array_equal() function is the simplest and most reliable way to compare two arrays. It checks whether:
Syntax:
numpy.array_equal(arr1, arr2)
Example: This code compares two arrays using np.array_equal() and prints whether they are equal.
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.
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.
True
Explanation: Every element matches, so result is True. If even one element was different, it would return False.
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.
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.