Sub topic 7
Combining conditions with &, |, and ~
This chapter assumes you can build a boolean mask from a comparison such as data > 0 and use it to filter an array. It also assumes you know what an array's shape and dtype are. Here you will combine several conditions into one mask.
Why `and` and `or` do not work
A single comparison gives one boolean array. Real filters usually need two or more conditions, such as "positive and even". Python's and, or, and not ask for one truth value for the whole object, so NumPy cannot apply them element by element.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
try:
data[(data > 0) and (data % 2 == 0)]
except ValueError as e:
print(e)The error says the truth value of an array with more than one element is ambiguous. NumPy cannot tell whether "true" means all elements, any element, or something else. Use the element-wise operators instead.
| Operator | Meaning | Python keyword it replaces | Column |
|---|---|---|---|
| `&` | element-wise AND | `and` | |
| `\ | ` | element-wise OR | `or` |
| `~` | element-wise NOT | `not` |
Combining two masks
Each operator takes boolean arrays of the same shape (or shapes that broadcast together) and returns a new boolean array.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
positive = data > 0
even = data % 2 == 0
print(positive & even) # [ True False False False False True]
print(data[positive & even]) # [4 2]
print(data[positive | even]) # [ 4 7 0 2]
print(data[~positive]) # [-1 0 -5]Naming the intermediate masks, as above, makes long filters easier to read and test. You can print each mask on its own to see where a condition goes wrong.
The diagram shows how two masks merge into one.
Always use parentheses
The operators &, |, and ~ bind more tightly than comparisons like > and ==. Without parentheses, Python reads the expression in an order you did not intend.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
# Wrong: parsed as data > (0 & data) % 2 == 0, a chained comparison
try:
data[data > 0 & data % 2 == 0]
except (ValueError, TypeError) as e:
print(type(e).__name__)
# Right: each comparison in its own parentheses
print(data[(data > 0) & (data % 2 == 0)]) # [4 2]The unparenthesized version fails or gives a wrong result, depending on the values. The fix is the same each time: wrap every comparison in parentheses.
Negating with `~`
~ flips each boolean. It is the right tool for "everything except". Use it only on boolean arrays. On integer arrays, ~ flips bits, so ~5 is -6.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
mask = data > 0
print(~mask) # [False True False True True False]
print(data[~mask]) # [-1 0 -5]
print(data[~(data > 0)]) # same result, with the condition inlineNote that ~(data > 0) is not the same as data < 0. The value 0 satisfies the first condition but not the second. Pick the form that matches what you mean.
Several conditions on a 2-D array
Masks work on any shape. A full-shape mask on a 2-D array returns a flattened 1-D result, because the selected elements no longer form a rectangle.
import numpy as np
a = np.arange(12).reshape(3, 4)
mask = (a > 2) & (a < 9) & (a % 2 == 0)
print(mask.sum()) # 3
print(a[mask]) # [4 6 8]Chain as many conditions as needed, each in parentheses. The .sum() call counts the True values, which is a quick way to check how many elements a filter selects.
Useful alternatives
np.logical_and,np.logical_or, andnp.logical_notdo the same work as the operators and avoid the precedence problem, but accept only two masks at a time forandandor.np.anyandnp.allreduce a mask to a single boolean, which is what Python'sandandorwere trying to ask for.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
print(np.logical_and(data > 0, data % 2 == 0)) # [ True False False False False True]
print((data > 0).any()) # True
print((data > 0).all()) # FalseExercise
Given x = np.array([10, 15, 20, 25, 30, 35]), write one expression that returns the elements that are either less than 15 or greater than 28, and explain why x[x < 15 or x > 28] fails.
Show answer
Use x[(x < 15) | (x > 28)], which returns [10 30 35]. The expression with or fails because or needs a single truth value for each side, and an array with several elements has no single truth value, so NumPy raises a ValueError. The | operator works element by element, and the parentheses stop | from binding before the comparisons.
Exercise
For a = np.arange(12).reshape(3, 4), what does a[~((a > 2) & (a < 9))] return, and what is its shape?
Show answer
It returns the elements that are not between 3 and 8, which are [0 1 2 9 10 11]. The shape is (6,), a 1-D array, because a full-shape mask flattens the result.