30

I'm trying to use the logical_and of two or more numpy arrays. I know numpy has the function logical_and(), but I find the simple operator & returns the same results and are potentially easier to use.

For example, consider three numpy arrays a, b, and c. Is np.logical_and(a, np.logical_and(b,c)) equivalent to a & b & c?

If they are (more or less) equivalent, what's the advantage of using logical_and()?

1
  • 9
    From docs.scipy.org/doc/numpy/reference/generated/… bitwise "Computes the bit-wise AND of the underlying binary representation of the integers in the input arrays" only applies to ints and Booleans. It is not quite the same as np.logical_and except when working with booleans
    – user1121588
    Oct 28, 2015 at 7:32

2 Answers 2

29

@user1121588 answered most of this in a comment, but to answer fully...

"Bitwise and" (&) behaves much the same as logical_and on boolean arrays, but it doesn't convey the intent as well as using logical_and, and raises the possibility of getting misleading answers in non-trivial cases (packed or sparse arrays, maybe).

To use logical_and on multiple arrays, do:

np.logical_and.reduce([a, b, c])

where the argument is a list of as many arrays as you wish to logical_and together. They should all be the same shape.

1
  • 8
    It is worth mentioning that the bitwise operations (such as &, etc.) are significantly faster than the corresponding function (such as logical_and) if speed is a concern. For me, it was around a 4x difference.
    – Torben545
    Jun 24, 2020 at 9:23
23

I have been googling some official confirmation that I can use & instead of logical_and on NumPy bool arrays, and found one in the NumPy v1.15 Manual:

If you know you have boolean arguments, you can get away with using NumPy’s bitwise operators, but be careful with parentheses, like this: z = (x > 1) & (x < 2). The absence of NumPy operator forms of logical_and and logical_or is an unfortunate consequence of Python’s design.

So one can also use ~ for logical_not and | for logical_or.

1
  • 7
    Precedence: NumPy’s & operator is higher precedence than logical operators like < and >; Matlab’s is the reverse. Exactly the reference I was looking for. Thanks.
    – Ombrophile
    May 7, 2020 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.