np.logical_and/or/not
logical_and, logical_or and logical_not combine conditions element by element.
In this page:
Syntax
np.logical_and(a, b)
np.logical_or(a, b)
np.logical_not(a)
np.logical_and/or/not
These functions are the named versions of &, | and ~ for boolean arrays. They accept any array-like input and treat non-zero as True. np.logical_xor is also available for exclusive or.
Note:
With the operators, remember to wrap each comparison in parentheses.
Example: np.logical_and/or/not
import numpy as np
a = np.array([1, 4, 7, 10, 13])
big = a > 5
even = a % 2 == 0
print(np.logical_and(big, even))
print(np.logical_or(big, even))
print(np.logical_not(big))
# Output:
# [False False False True False]
# [False True True True True]
# [ True True False False False]
Related Topics
Common Mistakes
- Using Python and or or on arrays
- Forgetting parentheses with & and |
- Applying ~ to non-boolean integers
Chapter Summary
- logical_and equals &
- logical_or equals |
- logical_not equals ~
- Combine masks to filter data
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: