This tutorial will discuss about unique ways to check if all elements in a numpy array are equal to value.
Table Of Contents
Technique 1: Using all() method
We can use the numpy.all() method to check if all elements of a NumPy array are equal to a given value.
Compare the NumPy array with the given value, and it will give a NumPy Array of boolean values. A True
value in this boolean NumPy Array represents that the corresponding value in the original array is equal to the given value. Then to confirm if all the values in this boolean array are True or not, pass this boolean array to the numpy.all() method. If it returns True, then it means that all the values in orignal NumPy array are same, and equal to the given value.
Let’s see the complete example,
Frequently Asked:
import numpy as np # Create a NumPy array arr = np.array([23, 23, 23, 23, 23, 23]) value = 23 # Check if all values in NumPy array are equal to a given value if np.all(arr == value): print(f"All elements in Array are equal to the given value") else: print(f"All elements in Array are not equal to the given value")
Output
All elements in Array are equal to the given value
It should also work with a 2D Numpy Array. Suppose we have 2D NumPy array, and we will use the same technique to check if all the values in this 2D Numpy array are equal.
Let’s see the complete example,
import numpy as np # Create a NumPy array arr = np.array([[16, 16, 16], [16, 16, 16], [16, 16, 16]]) value = 16 # Check if all values in 2D NumPy array are equal to a given value if np.all(arr == value): print(f"All elements in Array are equal to the given value") else: print(f"All elements in Array are not equal to the given value")
Output
Latest Python - Video Tutorial
All elements in Array are equal to the given value
Technique 2: using array_equal() method
Create an array of equal size but with the repeated values, and this value should be equal to the given value. Then match this new NumPy Array with the original array, using the numpy.array_equal() method. If both the arrays are equal, then it means that all the elements in original NumPy array are equal to the given value.
Let’s see the complete example,
import numpy as np # Create a NumPy array arr = np.array([23, 23, 23, 23, 23, 23]) value = 23 # Create another array of same size but with repeated value # Check if both the arrays are equal if np.array_equal(arr, np.full_like(arr, value)): print(f"All elements in Array are equal to the given value") else: print(f"All elements in Array are not equal to the given value")
Output
All elements in Array are equal to the given value
Summary
We learned about different ways to check if all values in a NumPy array are equal to a value in Python. Thanks.
Latest Video Tutorials