Kodeclik Blog

How to check if two numpy arrays are equal

When working with Numpy arrays, we will sometimes feel the need to compare them and check if they are equal, i.e., if they are equal when comparisons are done element-wise. The numpy.equal() function takes two numpy arrays as input and does precisely this - after doing an element-wise comparison returning an output boolean array of results.

Example of numpy.equal() in action

Here is a simple program to explore this:
In this program, we create two arrays with elements [1,2] and [1,3] respectively and then use numpy.equal() on these arrays. The output is:
revealing that the (respective) first elements are equal but the second elements are not.

Using numpy.equal() with arrays of different sizes

If we try this:
we will get this error:
meaning that the two arrays are not broadcastable to a common shape (which becomes the shape of the output).

Using numpy.equal() with two dimensional arrays

Here we will use numpy.arange() to first generate values in a certain interval and then numpy.reshape() to organize them into a two dimensional array:
The first array will have values from 0 to 8 and the second will have values from 1 to 9. As a result even though they are of the same size (4 rows and 2 columns), they will not have element-wise the same values, so np.equal() will return all False’s. The output is thus:

Using numpy.equal() with 2D arrays having the same values but different sizes

In this example, we will create two arrays with the same values but reshape them into different sizes. As a result numpy.equall() will fail.
The output is:

Shorthand for numpy.equal is ==

We can use the == operator to do the same operations we have been doing thus far.
Thus, the following program:
To summarize, checking for equality between two numpy arrays is really easy, either with numpy.equal() or the == operator. The array sizes have to match up exactly, in order to allow an element-wise comparison. An aggregate True or False is not returned; instead an element-wise True or False is returned (which we can then aggregate if needed).
For more understanding of numpy arrays, checkout our blogpost on creating numpy arrays from lists.
For more Python content, checkout the math.ceil() and math.floor() functions! Also learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2023. All rights reserved.