Check if two arrays are equal Python

NumpyServer Side ProgrammingProgramming

To return True if all entries of two arrays are equal, use the ma.allequal() method in Python Numpy. Returns True if the two arrays are equal within the given tolerance, False otherwise. If either array contains NaN, then False is returned.

The fill_value sets whether masked values in a or b are considered equal (True) or not (False). A masked array is the combination of a standard numpy.ndarray and a mask. A mask is either nomask, indicating that no value of the associated array is invalid, or an array of booleans that determines for each element of the associated array whether the value is valid or not.

Steps

At first, import the required library −

import numpy as np

Create an array, 3x3 array with int elements using the numpy.arange() method −

arr1 = np.arange(9).reshape((3,3)) print("Array1...", arr1) print("Array type...

", arr1.dtype)

Create masked array1 −

arr1 = ma.array(arr1)

Mask Array1 −

arr1[0, 1] = ma.masked arr1[1, 1] = ma.masked

Display Masked Array 1 −

print("Masked Array1...

",arr1)

Creating another array, a 3x3 array with int elements using the numpy.arange() method −

arr2 = np.arange(9).reshape((3,3)) print("Array2...", arr2) print("Array type...

", arr2.dtype)

Create another masked array2 −

arr2 = ma.array(arr2)

Mask Array2 −

arr2[2, 1] = ma.masked arr2[2, 2] = ma.masked

Display Masked Array 2 −

print("Masked Array2...

",arr2)

To return True if all entries of two arrays are equal, use the ma.allequal() method in Python Numpy −

print("Result...

",ma.allequal(arr1, arr2))

Example

import numpy as np import numpy.ma as ma # Array 1 # Creating a 3x3 array with int elements using the numpy.arange() method arr1 = np.arange(9).reshape((3,3)) print("Array1...", arr1) print("Array type...", arr1.dtype) # Get the dimensions of the Array print("Array Dimensions...",arr1.ndim) # Get the shape of the Array print("Our Array Shape...",arr1.shape) # Get the number of elements of the Array print("Elements in the Array...",arr1.size) # Create a masked array arr1 = ma.array(arr1) # Mask Array1 arr1[0, 1] = ma.masked arr1[1, 1] = ma.masked # Display Masked Array 1 print("Masked Array1...",arr1) # Array 2 # Creating another 3x3 array with int elements using the numpy.arange() method arr2 = np.arange(9).reshape((3,3)) print("Array2...", arr2) print("Array type...", arr2.dtype) # Get the dimensions of the Array print("Array Dimensions...",arr2.ndim) # Get the shape of the Array print("Our Array Shape...",arr2.shape) # Get the number of elements of the Array print("Elements in the Array...",arr2.size) # Create a masked array arr2 = ma.array(arr2) # Mask Array2 arr2[2, 1] = ma.masked arr2[2, 2] = ma.masked # Display Masked Array 2 print("Masked Array2...",arr2) # To Return True if all entries of two arrays are equal, use the ma.allequal() method in Python Numpy print("Result...

",ma.allequal(arr1, arr2))

Output

Array1... [[0 1 2] [3 4 5] [6 7 8]] Array type... int64 Array Dimensions... 2 Our Array Shape... (3, 3) Elements in the Array... 9 Masked Array1... [[0 -- 2] [3 -- 5] [6 7 8]] Array2... [[0 1 2] [3 4 5] [6 7 8]] Array type... int64 Array Dimensions... 2 Our Array Shape... (3, 3) Elements in the Array... 9 Masked Array2... [[0 1 2] [3 4 5] [6 -- --]] Result... True

Check if two arrays are equal Python

Updated on 22-Feb-2022 10:13:09

How to check if NumPy Array equal or not? By using Python NumPy np.array_equal() function or == (equal operator) you check if two arrays have the same shape and elements. These return True if it has the same shape and elements, False otherwise. There are also other ways to check if two NumPy arrays are equal or not.

In this article, I will explain how to check if two arrays are equal or not by using the following approaches. By using these we can carry out an element-wise equality comparison on NumPy arrays.

  • array_equal() Function
  • Equal Operator (==)
  • array_equiv() Function
  • allclose() Function

1. Quick Examples of Python NumPy Array Equal

If you are in a hurry, below are some quick examples of how to check if two Python NumPy arrays are equal or not.

# Below are the quick examples # Create NumPy array arr = np.array([2,4,5,7,9]) arr1 = np.array([2,4,5,7,9]) # Example 1: Using array_equal() np.array_equal(arr, arr1) # Example 2: Using == operator and all() method print((arr == arr1).all()) # Example 3: use numpy.allcloses() function to numpy array equal arr2 = np.allclose(arr, arr1) # Example 4: Use numpy.array_equiv() function np.array_equiv(arr, arr1)

2. Using == Operator and all() Method

2.2 Check Array Equal Element Wise using == Operator

Like any other programming language, you can use the equal comparison operator (==) to check if two NumPy arrays are equal or not. This operator checks element by element and returns the array with the result for each element. The following example compares arr and arr1 objects element-wise and returns the array with boolean values either True for matching and False for not matching.

import numpy as np arr = np.array([2,4,5,7,9]) arr1 = np.array([2,4,6,7,10]) # Using == operator and all() method print(arr == arr1) # Output #[ True True False True False]

2.3 Check Two Arrays are Exactly Equal

If you wanted a single value whether all elements in an array are matched or not use all() function on the result of the == equal condition.

arr = np.array([2,4,5,7,9]) arr1 = np.array([2,4,6,7,10]) # Using == operator and all() method print((arr == arr1).all()) # Output # False

Now let’s use the same array and check the result. The below example returns True as all elements of both arrays are exactly the same.

arr = np.array([2,4,5,7,9]) arr1 = np.array([2,4,5,7,9]) # Using == operator and all() method print((arr == arr1).all()) # Output # True

3. Using array_equal()

You can also use numpy.array_equal() function to check if two elements are exactly the same or not. This function takes the arrays you wanted to compare and equal_nan param whether to consider nan values or not in the comparison.

3.1 Syntax of numpy.array_equal()

Following is the syntax of the numpy.array_equal() function.

# Syntax of Use numpy.array_equal() numpy.array_equal(arr, arr1, equal_nan=False)

Following are the parameters of numpy.array_equal().

  • arr - The first input array.
  • arr1 - The second input array.
  • equal_nan - Whether to compare NaN’s as equal. If the dtype of arr and arr1 is complex, values will be considered equal if either the real or the imaginary component of a given value is nan.

3.2 numpy.array_equal() Example

In the below example we are comparing two arrays that contain same values hence, it returns True.

arr = np.array([2,4,5,7,9]) arr1 = np.array([2,4,5,7,9]) # Using == operator and all() method print(np.array_equal(arr,arr1)) # Output # True

4. Use numpy.allcloses() Function to NumPy Array Equal

We can use numpy.allclose() function to check if two arrays are element-wise equal or not in Python. The numpy.allclose() function returns True if all the elements inside both arrays are equal within a specified tolerance. In the below code, we used the np.allclose() function to check if arr is equal to arr1.

# Use numpy.allcloses() function to numpy array equal arr2 = np.allclose(arr, arr1) print(arr2) # Output # True

5. Use numpy.array_equiv() Function

You can also use numpy.array_equiv() function to check whether two arrays are equal or not in Python. This function returns True if both arrays have the same shape and all the elements are equal and return False otherwise.

import numpy as np arr = np.array([2,4,5,7,9]) arr1 = np.array([2,3,5,8,9]) # Use numpy.array_equiv() function arr2 = np.array_equiv(arr, arr1) print(arr2) # Output # False

Conclusion

In this article, I have explained different ways how to check if two NumPy arrays are equal by checking shape and values element-wise. Here, I used methods == operator, np.array_equal(), np.array_equiv(), and np.allclose() functions.

Happy Learning!!

References

  • https://numpy.org/doc/stable/reference/generated/numpy.array_equal.html

In this article we will learn How to check if two NumPy Arrays are equal.

Table Of Contents

Given Two NumPy arrays we need to check if every element of array is same as other array then we can say that arrays are equal

Example 1:

a = np.array([1,2,3,4,5,6]) b = np.array([1,2,3,4,5,6])

Both are arrays are considered to be equal, As all the elements are same.

Example 2:

a = np.array([1,2,3,4,5,6]) b = np.array([7,3,3,4,5,6])

Both are arrays are considered to be Not equal, As all the elements are Not same.

There are multiple ways of checking if two numpy arrays are equal or not. Lets discuss all the methods one by one with proper approach and a working code example

1. Using == operator and all() method

The two numpy arrays when compared using the == operator returns a array of boolean values with length same as the comparing arrays. The boolean array represents at which positions elements in both arrays are equal. The True value represents that element in both arrays are equal at that specific position and False represent that element in both arrays are equal at the corresponding position.

The all() method is used to check if all the elements present in the array are equal to True, The all() method takes array as input parameter and returns a boolean value.

Syntax of all()

numpy.all(array, axis = None)

Approach

  1. import numpy library and create two numpy arrays
  2. Check if both arrays are of equal shape using shape() method
  3. compare them using == operator and it returns a boolean array
  4. Apply all() method on boolean array, if it returns true then print arrays are equal else print arrays are nto
    equal.

Source code

import numpy as np # creating two numpy arrays a = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) b = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) # checking if both the arrays are of equal size if a.shape == b.shape: # comparing the arrays using == and all() method if (a == b).all(): print("Arrays are equal") else: print("Arrays are not equal") else: print("Arrays are not equal")

OUTPUT:

Arrays are equal

2. Using array_equal() method

The array_equal() method is a built-in numpy method, it takes two arrays as arguments and returns a boolean value, True represent that the arrays are equal and false represent that the arrays are not equal.

Syntax of array_equal()

numpy.array_equal(array_1, array_2)

Approach

  • Import numpy library and create two numpy arrays
  • Check if both arrays are of equal shape using shape() method
    • If shape of two arrays is not equal then print arrays not equal else move to next step
  • Pass the two arrays to array_equal() method, if it returns true print arrays are equal else print arrays are not equal.

Source code

import numpy as np # creating two numpy arrays a = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) b = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) # Comparing both arrays using array_equal() method if np.array_equal(a, b): print("Arrays are Equal") else: print("Arrays are not equal")

OUTPUT:

Arrays are Equal

3. Flattening the arrays and comparing elements one-by-one

The flatten() method is a built-in numpy method, it takes an array as arguments and returns a flattened array i.e. 1d array. Now these flatten arrays can be iterated with ease.

Syntax of flatten()

ndarray.flatten()

Approach

  • import numpy library and create two numpy arrays
  • Check if both arrays are of equal shape using shape() method
    • If shape of two arrays is not equal then print arrays not equal else move to next step
  • Initialize as boolean flag and set it to False.
  • Flatten both the arrays using flatten() method
  • Iteratively compare the each element of the both arrays using for loop
    • If any of the element is not equal then set the not_equal flag to True and break the loop
  • Outside the loop check the not_equal flag and if it is true print the arrays are not else print arrays are equal

Source code

import numpy as np # creating two numpy arrays a = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) b = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) #initialise boolean flag not_equal = False # checking if both the arrays are of equal size if a.shape == b.shape: # flattening both the arrays using flatten() method a = a.flatten() b = b.flatten() # iterating elements from both arrays at once using zip() for i, j in zip(a, b): if i != j: # if any element is not equal set not_equal flag to true and break not_equal = True break if not not_equal: print("Arrays are equal") else: print("Arrays are not equal") else: print("Arrays are not equal")

OUTPUT:

Arrays are equal

4. Flattening the arrays using ravel() method and comparing elements one-by-one

This Approach is almost similar to the previous one, but the only diffrence is we use ravel() method to flatten the array and rest remains same. The ravel() method is a built-in numpy method, it takes an array as arguments and returns a flattened array i.e. 1d array. Now these flattened arrays can be iterated with ease.

Syntax of ravel()

ndarray.ravel()

Approach

  • import numpy library and create two numpy arrays
  • Check if both arrays are of equal shape using shape() method
    • If shape of two arrays is not equal then print arrays not equal else move to next step
  • Initialize as boolean flag and set it to False.
  • Flatten both the arrays using ravel() method
  • Iteratively compare the each element of the both arrays using for loop
    • If any of the element is not equal then set the not_equal flag to True and break the loop
  • Outside the loop check the not_equal flag and if it is true print the arrays are not else print arrays are equal

Source code

import numpy as np # creating two numpy arrays a = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) b = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) #initialise boolean flag not_equal = False # checking if both the arrays are of equal size if a.shape == b.shape: # flattening both the arrays using ravel() method a = a.ravel() b = b.ravel() # iterating elements from both arrays at once using zip() for i, j in zip(a, b): if i != j: # if any element is not equal set not_equal flag to true and break not_equal = True break if not not_equal: print("Arrays are equal") else: print("Arrays are not equal") else: print("Arrays are not equal")

OUTPUT:

Arrays are equal

5. Using array_equiv() method

The array_equiv() method is a built-in numpy method, it takes two arrays as arguments and returns a boolean value, True represent that the arrays are equal and false represent that the arrays are not equal.

Syntax of array_equiv()

numpy.array_equiv(array_1, array_2)

Approach

  • Import numpy library and create two numpy arrays
  • Check if both arrays are of equal shape using shape() method
    • If shape of two arrays is not equal then print arrays not equal else move to next step
  • Pass the two arrays to array_equiv() method, if it returns true print arrays are equal else print arrays are not equal.

Source code

import numpy as np # creating two numpy arrays a = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) b = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) # Comparing both arrays using array_equiv() method if np.array_equiv(a, b): print("Arrays are Equal") else: print("Arrays are not equal")

OUTPUT:

Arrays are Equal

6. Using Numpy nditer() to iterate over the elements in array and compare one-by-one

The nditer() is a built-in numpy function, it takes an array as an argument. nditer() is used for very basic iterations to advanced iterations. It provides Efficient multi-dimensional iterator object to iterate over arrays.

Syntax of nditer()

numpy.nditer(op, flags=None)

Approach

  • Import numpy library and create two numpy arrays
  • Check if both arrays are of equal shape using shape() method
    • If shape of two arrays is not equal then print arrays not equal else move to next step
  • Pass the each array to numpy.nditer(), It helps in very Efficient iteration of multi-dimensional numpy arrays.
  • Iterate over the itertor created using nditer and compare each element of the both arrays
    • If any of the element is not equal then set the not_equal flag to True and break the loop
  • Outside the loop check the not_equal flag and if it is true print the arrays are not else print arrays are equal equal.

Source code

import numpy as np # creating two numpy arrays a = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) b = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) #initialise boolean flag not_equal = False # checking if both the arrays are of equal size if a.shape == b.shape: # passing arrays to nditer() for i, j in zip(np.nditer(a), np.nditer(b)): #checking if two variables are equal or not if i != j: not_equal = True break if not not_equal: print("Arrays are equal") else: print("Arrays are not equal") else: print("Arrays are not equal")

OUTPUT:

Arrays are equal

7. Using allclose() method

The allclose() method is a built-in numpy method, it takes two arrays as arguments and atol (absolute tolerance), rtol (relative tolerance) as optional arguments which are used to specify the tolerance i.e the value by which values can differ and returns a boolean
value, True represent that the elements in the arrays are very very close to each other (i.e equal) and false represent that the arrays are not equal.

NOTE: In the case of checking equality of two arrays we set the atol=0 and rtol=0 so that the allclose() will return true only when all the elements of both arrays are exactly equal

Syntax of allclose()

np.allclose(a, b,rtol=0, atol=0)

Approach

  • Import numpy library and create two numpy arrays
  • Check if both arrays are of equal shape using shape() method
    • If shape of two arrays is not equal then print arrays not equal else move to next step
  • Pass the two arrays to allclose() method, if it returns true print arrays are equal else print arrays are not equal.

Source code

import numpy as np # creating two numpy arrays a = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) b = np.array([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]) # Comparing both arrays using allclose() method if np.allclose(a, b,rtol=0, atol=0): print("Arrays are Equal") else: print("Arrays are not equal")

OUTPUT:

Arrays are Equal

Summary

We learned about different ways to check if two NumPy Arrays are equal or not in Python.