Sub topic 7
Combining conditions with &, |, and ~
A single comparison such as data > 0 gives you one boolean mask. Real filters usually need several conditions at once: values inside a range, values outside it, or values that meet one condition but not another. This chapter covers how to combine masks with &, |, and ~, why Python's and, or, and not fail on arrays, and which mistakes pass silently.
It assumes you can build a boolean mask from a comparison and use it to index an array (the previous chapter). It also assumes you know what an array's shape and dtype are.
Why `and`, `or`, and `not` fail
Python's and and or ask each operand a yes-or-no question: "is this object true?" An array with many elements has no single answer, so NumPy refuses.
import numpy as np
temps = np.array([12.5, 31.0, 18.2, 35.4, 7.8, 22.0, 29.9])
try:
temps[(temps > 10) and (temps < 30)]
except ValueError as err:
print(err)This prints The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
The error message suggests .any() or .all(). Those reduce the mask to one boolean, which is almost never what you want when filtering. You want to combine the masks element by element. NumPy overloads three operators for that:
| Operator | Meaning | Equivalent function | Column |
|---|---|---|---|
| `a & b` | True where both are true (AND) | `np.logical_and(a, b)` | |
| `a \ | b` | True where at least one is true (OR) | `np.logical_or(a, b)` |
| `~a` | True where `a` is false (NOT) | `np.logical_not(a)` | |
| `a ^ b` | True where exactly one is true (XOR) | `np.logical_xor(a, b)` |
Building combined masks
Each comparison produces its own mask. The operators then merge two masks into a third mask of the same shape.
import numpy as np
temps = np.array([12.5, 31.0, 18.2, 35.4, 7.8, 22.0, 29.9])
mild = (temps > 10) & (temps < 30)
print(mild) # [ True False True False False True True]
print(temps[mild]) # [12.5 18.2 22. 29.9]
extreme = (temps < 10) | (temps > 35)
print(extreme) # [False False False True True False False]
print(temps[extreme]) # [35.4 7.8]
print(temps[~mild]) # [31. 35.4 7.8]~mild is exactly the complement of mild, so temps[mask] and temps[~mask] together cover every element once.
Operator precedence: always use parentheses
The most common indexing bug in this area comes from precedence. In Python, &, |, and ^ bind more tightly than comparison operators like > and <. Without parentheses, the expression is not parsed the way it reads.
import numpy as np
temps = np.array([12.5, 31.0, 18.2, 35.4, 7.8, 22.0, 29.9])
try:
temps > 10 & temps < 30
except TypeError as err:
print(type(err).__name__) # TypeErrorPython reads temps > 10 & temps < 30 as temps > (10 & temps) < 30. The 10 & temps part is a bitwise AND, which floats don't support, so you get a TypeError. With an integer array the same mistake gives a different error, because the chained comparison ends up calling and on arrays, which raises the ValueError you saw earlier.
The rule is simple: wrap every comparison in its own parentheses before using & or |.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
print(data[(data > 0) & (data % 2 == 0)]) # [4 2]The ~ operator has the same problem in a quieter form. It binds tighter than >, so ~data > 0 means (~data) > 0. On an integer array, ~ is bitwise NOT, which maps each value n to -n - 1. The result is a valid mask, so no error appears, and it is wrong.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
print(~(data > 0)) # [False True False True True False] intended
print(~data > 0) # [False False False False True False] silently wrong`~` needs a boolean array
~ means "logical not" only for boolean arrays. On integer arrays it flips bits. This matters when a mask has been converted to integers, for example by .astype(int) or by arithmetic.
import numpy as np
mask = np.array([True, False, True])
as_int = mask.astype(int)
print(~mask) # [False True False]
print(~as_int) # [-2 -1 -2]If you then index with ~as_int, NumPy treats -2 and -1 as integer positions (fancy indexing), not as a mask. The result looks like a selection of the wrong elements. Keep masks as bool dtype, or use np.logical_not, which converts non-boolean input to booleans first.
Functions versus operators
np.logical_and and np.logical_or do the same job as & and | on boolean arrays. They have two practical advantages. They don't need parentheses around their arguments, because the arguments are already separate expressions. They also work with .reduce, which combines any number of masks.
import numpy as np
temps = np.array([12.5, 31.0, 18.2, 35.4, 7.8, 22.0, 29.9])
conditions = [temps > 10, temps < 30, temps != 22.0]
combined = np.logical_and.reduce(conditions)
print(combined) # [ True False True False False False True]
print(temps[combined]) # [12.5 18.2 29.9]np.logical_and(a, b, c) does not work as a three-way AND. The third positional argument is the out parameter, so use reduce for more than two masks. Swap in np.logical_or.reduce for a combined OR.
The operators are shorter for two or three conditions. The reduce form is easier when the number of conditions is only known at run time, for example when filters come from user settings.
Both sides are always evaluated
Python's and skips its right side when the left side is already false. & never skips anything. NumPy computes both masks over the whole array before combining them. That matters when the second condition is only safe where the first one is true.
import numpy as np
v = np.array([0.0, 2.0, 4.0, 0.5])
with np.errstate(divide="ignore"):
ok = (v != 0) & (1 / v > 0.4)
print(ok) # [False True False True]
print(v[ok]) # [2. 0.5]1 / v is computed for the zero element too, giving inf and a divide warning. The warning is suppressed here with np.errstate. The first condition still gives the right final answer, because False & True is False. Guards like this keep the result correct, but they don't prevent the computation or its warnings. For conditions that can raise real errors, compute the safe subset first, or use np.divide(..., where=...) and similar functions with a where argument.
NaN values and `~`
Any comparison involving NaN is false, including nan != nan being true and nan == nan being false. That produces a trap when you negate a mask.
import numpy as np
x = np.array([1.0, np.nan, -2.0, 4.0])
print(x > 0) # [ True False False True]
print(~(x > 0)) # [False True True False]
print(x[~(x > 0)]) # [nan -2.]
valid = ~np.isnan(x)
print(x[valid & (x > 0)]) # [1. 4.]~(x > 0) means "not greater than zero", which includes NaN. If you meant "less than or equal to zero", write x <= 0, which excludes NaN. When data may contain NaN, add ~np.isnan(x) explicitly so the intent is clear.
Many alternatives with `np.isin`
A chain of | over equality checks grows quickly. np.isin expresses "is one of these values" directly.
import numpy as np
codes = np.array([1, 2, 3, 2, 5, 3, 1])
chained = (codes == 2) | (codes == 3)
print(chained) # [False True True True False True False]
print(codes[np.isin(codes, [2, 3])]) # [2 3 2 3]
print(codes[~np.isin(codes, [2, 3])]) # [1 5 1]Combining masks on 2-D arrays
A mask built from a 2-D array has the same 2-D shape. Indexing with it returns a flattened 1-D result of the matching values. To select whole rows or columns, reduce the mask along an axis with .all(axis=...) or .any(axis=...), or build a 1-D mask from one column.
import numpy as np
scores = np.array([[82, 91, 47],
[60, 38, 75],
[95, 88, 52]])
passed = scores >= 50
print(passed)
# [[ True True False]
# [ True False True]
# [ True True True]]
print(passed.sum()) # 7, number of passing scores
print(passed.all(axis=1)) # [False False True]
print(scores[passed.all(axis=1)]) # [[95 88 52]]
strong = (scores >= 80) & (scores < 90)
print(np.count_nonzero(strong)) # 2
row_mask = (scores[:, 0] > 70) & (scores[:, 2] < 60)
print(scores[row_mask])
# [[82 91 47]
# [95 88 52]]
col_mask = scores.mean(axis=0) > 60
print(scores[:, col_mask])
# [[82 91]
# [60 38]
# [95 88]]Booleans count as 0 and 1 in arithmetic, so .sum() and np.count_nonzero give the number of matches. A 1-D mask used as the row index must have exactly as many entries as there are rows, and a column mask must match the number of columns. A length mismatch raises an IndexError that names the axis.
Common mistakes at a glance
| Symptom | Likely cause | Fix | Column |
|---|---|---|---|
| `ValueError: truth value of an array ... is ambiguous` | `and`, `or`, `not`, or a chained comparison like `0 < x < 5` | Use `&`, `\ | `, `~`, and write `(x > 0) & (x < 5)` |
| `TypeError` mentioning `bitwise_and` | Missing parentheses around comparisons | Parenthesize each comparison | |
| Plausible but wrong selection | `~x > 0` instead of `~(x > 0)` | Parenthesize, or use the opposite comparison | |
| Odd rows or elements selected after negation | Mask was converted to int, so `~` flipped bits | Keep dtype `bool`, or use `np.logical_not` | |
| `NaN` rows appear after `~` | Negating a false comparison includes `NaN` | Add `~np.isnan(x)` | |
| `IndexError: boolean index did not match` | Mask length differs from the axis length | Check `mask.shape` against the axis you index |
Exercise
Given a = np.array([3, 8, 12, 5, 20, 7]), write one expression that returns the elements that are NOT between 5 and 10 inclusive. Give two versions: one using ~ and one using | only.
Show answer
With ~: a[~((a >= 5) & (a <= 10))]. With |: a[(a < 5) | (a > 10)]. Both return [ 3 12 20 ]. The parentheses around the comparisons are required in both, and the ~ version needs an extra pair around the whole & expression.
Exercise
With data = np.array([4, -1, 7, 0, -5, 2]), what does print(data[~data > 0]) select, and why is it not the negative-or-zero values?
Show answer
It selects only -5. Because ~ binds tighter than >, the code runs (~data) > 0. On integers ~n equals -n - 1, so ~data is [-5, 0, -8, -1, 4, -3], and only 4 is greater than 0, which sits at the position of -5. The intended filter is data[~(data > 0)] or data[data <= 0], which returns [-1 0 -5].
Exercise
x = np.array([2.0, np.nan, 9.0, 5.0]). Write a filter that keeps values greater than 3 and less than 8, and explain why NaN is excluded without a special check.
Show answer
x[(x > 3) & (x < 8)] returns [5.]. Every comparison with NaN is False, so the NaN position is False in both masks and False after &. A special check is only needed when you negate a mask with ~, because ~False is True.