This is question is not a duplicate of another question. The other question asks about a single boolean output (
True/False
) when a conditional statement is applied on a numpy array. That's why it is important to usenp.any()
ornp.all()
to determine the output unambiguously.My question here talks about creating an element-wise array-output of boolean
True/False
values, when we evaluate if an arraya
is between2
and5
using an expression2 < a < 5
. This question delves into the viability of such a convenience expression while usingnumpy
arrays.
Python allows the following for a scalar.
a = 7
print(2 < a < 5) # False
a = 4
print(2 < a < 5) # True
However, if I try the same with a numpy array it does not work.
import numpy as np
a = np.arange(10)
2 < a < 5
This gives an error. But, any of the following two methods works (as expected):
np.logical_and(2 < a, a < 5) # method-1
(2 < a) & (a < 5) # method-2
Output:
array([False, False, False, True, True, False, False, False, False,
False])
So, my question is: is there any numpy equivalent such that you could just write 2 < a < 5
and get the above output?