How to Compare Two Arrays in Python?

Estimated read time 2 min read

To compare two arrays in Python, you can use the NumPy library, which provides various functions for array comparison. Here are a few common approaches:

  1. Element-wise comparison: You can compare the elements of two arrays directly to check for equality or inequality. The result is a new Boolean array indicating whether each element is equal or not.
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 4, 3])

result = arr1 == arr2
print(result)

Output:

[ True False  True]

In this example, we compare each element of arr1 with the corresponding element of arr2. The resulting Boolean array result indicates whether the elements are equal or not.

  1. Array-wise comparison: If you want to check whether two arrays are equal element-wise, you can use the array_equal() function from NumPy.
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 3])

result = np.array_equal(arr1, arr2)
print(result)

Output:

True

In this example, the np.array_equal() function compares the entire arrays arr1 and arr2 element-wise. The result is a Boolean value indicating whether the arrays are equal or not.

  1. Numerical tolerance comparison: If you are comparing arrays with floating-point values, you may want to use a tolerance to handle potential rounding errors. The allclose() function from NumPy can be used for such comparisons.
import numpy as np

arr1 = np.array([0.1, 0.2, 0.3])
arr2 = np.array([0.11, 0.2, 0.3])

result = np.allclose(arr1, arr2, rtol=1e-05, atol=1e-08)
print(result)

Output:

False

In this example, the np.allclose() function compares the arrays arr1 and arr2 within a specified relative tolerance (rtol) and absolute tolerance (atol). The result is a Boolean value indicating whether the arrays are close within the specified tolerances or not.

By using these approaches, you can compare two arrays in Python based on your specific requirements. Remember to import the NumPy library (import numpy as np) before using these functions.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply