2

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.

3
  • I don't see the OR operator. Commented Mar 6, 2015 at 14:26
  • Arithmetic operations on numpy booleans are cheesy, it is not the best of ideas to rely on them. Plus they make your code obscure and hard to interpret. If dealing with boolean arrays, use the bitwise operators: & for and, | for or, ^ for xor and ~ for not. Commented Mar 6, 2015 at 16:54
  • In case an answer solved your problem, please accept it as the solution like here Commented Mar 9, 2015 at 17:06

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

My opinion only, but | should always be preferred over +. When I see + I start wondering why we are adding stuff together, or if in fact we are concatenating stuff. As soon as I see | I think of bitwise_or which I closely associate with logical_or.
2

@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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.