Check if two NumPy Arrays are equal in Python

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

Table Of Contents

  1. Using == operator and all() method
  2. Using array_equal() method
  3. Flattening the arrays and comparing elements one-by-one
  4. Flattening the arrays using ravel() method and comparing elements one-by-one
  5. Using array_equiv() method
  6. Using Numpy nditer() method
  7. Using allclose() method

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.

Advertisements

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.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top