Reputation: 1493
To know the elements of a numpy array that verifies two conditions, one can use the operator *
:
>>> a = np.array([[1,10,2],[2,-6,8]])
>>> a
array([[ 1, 10, 7],
[ 2, -6, 8]])
>>> (a <= 6) * (a%2 == 0) # elements that are even AND inferior or equal to 6
array([[False, False, False],
[ True, True, False]], dtype=bool)
But how about OR? I tried to do this:
>>> (a%2 == 0) + (a <= 6) - (a%2 == 0) * (a <= 6)
array([[ True, True, False],
[False, False, True]], dtype=bool)
but the result is false for the elements that verifies both conditions. I don't understand why.
Upvotes: 2
Views: 2277
Reputation: 177098
@plonser's answer is the correct one: use +
.
If you wanted to use multiplication again, you could remember that one of De Morgan's laws tells you that
A or B
is logically equivalent to
not ( not A and not B )
So in NumPy you could write:
>>> ~(~(a%2 == 0) * ~(a <= 6))
array([[ True, True, True],
[ True, True, True]], dtype=bool)
But this isn't particularly readable.
Upvotes: 2
Reputation: 3363
You don't need the subtraction.
The point is that +
already behaves like the or
operator
>>(a%2==0)+(a<=6)
array([[ True, True, True],
[ True, True, True]], dtype=bool)
because "True+True=True
".
When you subtract (a<=6)*(a%2==0)
you turn all elements which satisfy both conditions into false
.
It is easiest when you just do
>>(a<=6)|(a%2==0)
array([[ True, True, True],
[ True, True, True]], dtype=bool)
Upvotes: 3