What would be the way to select elements when two conditions are True
in a matrix?
In R, it is basically possible to combine vectors of booleans.
So wha
you could just use &
, eg:
x = np.arange(10)
(x<8) & (x>2)
gives
array([False, False, False, True, True, True, True, True, False, False], dtype=bool)
A few details:
&
is shorthand for the numpy ufunc bitwise_and
, which for the bool
type is the same as logical_and
. That is, this could also be spelled out asbitwise_and(less(x,8), greater(x,2))
&
has higher precedence than <
and >
and
does not work because it is ambiguous for numpy arrays, so rather than guess, numpy raise the exception.While this is primitive, what is wrong with
A = [2, 2, 2, 2, 2]
b = []
for i in A:
b.append(A[i]>1 and A[i]<3)
print b
The output is [True, True, True, True, True]
There's a function for that:
In [8]: np.logical_and(A < 3, A > 1)
Out[8]: array([ True, True, True, True, True], dtype=bool)
Since you can't override the and
operator in Python it always tries to cast its arguments to bool
. That's why the code you have gives an error.
Numpy has defined the __and__
function for arrays which overrides the &
operator. That's what the other answer is using.