In this tutorial, we will look at how to check if all the values in a numpy array are within a specified range with the help of some examples.
How to check if array elements are within a range?
You can use a combination of comparison operators, the
& operator and the numpy
all() function to check if all the values in a numpy array lie within a given range, for example, low to high.
The following is the syntax –
# check if all values in numpy array in the range [low, high] ((ar >= low) & (ar <= high)).all()
The idea is to check whether each value in the array is greater than or equal to
low and less than or equal to
high. Comparing an array with a scalar value in numpy results in a boolean array, you can combine the results from both the boolean array using the
& operator to make sure both the conditions are met and then finally check whether all the values in the resulting boolean array are
True or not using the
If you do not want the range limits to be inclusive, use
< instead of
Let’s now look at some examples of using the above syntax –
Example – Check array values lie in a range
import numpy as np # create a 1d array ar = np.array([1, 2, 3, 5]) # check if array values lie in the range [0, 7] print(((ar >= 0) & (ar <= 7)).all())
In the above example, we create an array with some integer values and then check whether all the array values lie in the range [0, 7] or not.
Alternatively, you can also use the
numpy.logical_and() method to combine two boolean arrays with an and operation.
# check if array values lie in the range [0, 7] print(np.logical_and(ar >= 0, ar <=7).all())
We get the same result as above.
Let’s now take an example, where the condition is violated. For example, in the above array, let’s check if all the values are within the range [0, 4].
# check if array values lie in the range [0, 4] # method 1 print(((ar >= 0) & (ar <= 4)).all()) # method 2 print(np.logical_and(ar >= 0, ar <=4).all())
False as the output from both methods which is the correct answer.
You might also be interested in –
- Numpy – Check If Array is 1d or 2d
- Numpy – Check if Array is all NaN
- How to Plot Histograms by Group in Pandas
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.