This python article focuses on comparisons between two arrays performed with NumPy. When two NumPy arrays are compared, every element at each corresponding index is checked to see if they are equivalent.
We’ll cover the following methods here:
- Compare array using === operator.
- using intersect1d() method.
- Compare python array using
array_equal
method. - Comare two array using
allclose()
method.
You can also checkout other python tutorials:
- Encode and Decode String in Python
- What is numpy.ones() and uses
- Python do while with Example
- How to Use Logging in Python
Option 1: Using === Operator
We can use == operator to compare two NumPy arrays to generate a new array object. We will use comparison.all()
the method with the new array object as nd array to return True if the two NumPy arrays are equivalent.
import numpy as np l1 = np.array([1, 2, 3, 4]) l2 = np.array([1, 2, 3, 4]) l3 = l1 == l2 equal_arrays = l3.all() print(equal_arrays)
The above code will output [ True True True True]
, indicating that all elements in the two arrays are equal.
Output:
True
Option 2: Using Numpy intersect1d()
We can use also use intersect1d() method to compare two NumPy array, We’ll pass both arrays as an argument into this method.
import numpy as np l1 = np.array([1, 2, 3, 4]) l2 = np.array([1, 2, 3, 4]) c = np.intersect1d(l1,l2) print(c)
Output:
[1, 2, 3, 4]
Option 3: Using Numpy array_equal function
Numpy.array_equal()
is a function that can be used to compare two numpy arrays. If the arrays are identical in terms of structure and elements, this function returns “True” else it returns “False”:
import numpy as np array1 = np.array([4, 6, 8]) array2 = np.array([4, 6, 8]) result = np.array_equal(array1, array2) print(result) # True
The above code will return true, indicating that the two arrays are equal.
Option 4: Using numpy.allclose()
The "numpy.allclose()"
function can be used to compare arrays of floating point numbers.
It returns “True” if the array elements are equal to within a specified range, Otherwise returns “False.”
import numpy as np array1 = np.array([4.0, 5.0, 8.0]) array2 = np.array([4.0, 5.0, 8.002]) result = np.allclose(array1, array2) print(result) # True
This will output True
, indicating that the two arrays are equal within the default tolerance.