Easy way to test if each element in an numpy array lies between two values?
PythonNumpyPython Problem Overview
I was wondering if there was a syntactically simple way of checking if each element in a numpy array lies between two numbers.
In other words, just as numpy.array([1,2,3,4,5]) < 5
will return array([True, True, True, True, False])
, I was wondering if it was possible to do something akin to this:
1 < numpy.array([1,2,3,4,5]) < 5
... to obtain ...
array([False, True, True, True, False])
I understand that I can obtain this through logical chaining of boolean tests, but I'm working through some rather complex code and I was looking for a syntactically clean solution.
Any tips?
Python Solutions
Solution 1 - Python
One solution would be:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
(a > 1) & (a < 5)
# array([False, True, True, True, False])
Solution 2 - Python
Another would be to use numpy.any
, Here is an example
import numpy as np
a = np.array([1,2,3,4,5])
np.any((a < 1)|(a > 5 ))
Solution 3 - Python
You can also center the matrix and use the distance to 0
upper_limit = 5
lower_limit = 1
a = np.array([1,2,3,4,5])
your_mask = np.abs(a- 0.5*(upper_limit+lower_limit))<0.5*(upper_limit-lower_limit)
One thing to keep in mind is that the comparison will be symmetric on both sides, so it can do 1<x<5
or 1<=x<=5
, but not 1<=x<5
Solution 4 - Python
In multi-dimensional arrays you could use the np.any()
option suggested or comparison operators, while using &
and and
will raise an error.
Example (on multi-dim array) using comparison operators
import numpy as np
arr = np.array([[1,5,1],
[0,1,0],
[0,0,0],
[2,2,2]])
Now use ==
if you want to check if the array values are inside a range, i.e A < arr < B, or !=
if you want to check if the array values are outside a range, i.e arr < A and arr > B :
(arr<1) != (arr>3)
> array([[False, True, False],
[ True, False, True],
[ True, True, True],
[False, False, False]])
(arr>1) == (arr<4)
> array([[False, False, False],
[False, False, False],
[False, False, False],
[ True, True, True]])