Boolean Indexing & Filtering
Comparing a NumPy array to a value doesn't return a single true/false — it returns a whole array of them, one per element. That boolean array can then be used directly to filter the original data.
A comparison produces a boolean array
>>> which days were hot?
import numpy as np temps = np.array([72, 65, 90, 58, 81]) hot = temps > 75 print(hot) print(temps[hot])
Output
[False False True False True] [90 81]
temps > 75 compares every element to 75 and returns a same-length array of True/False values. Using that boolean array as an index — temps[hot] — pulls out only the elements where the mask is True. You can skip the intermediate variable entirely and write temps[temps > 75] in one line.
Combining multiple conditions
To combine conditions, use & (and) and | (or) — not Python's and/or — with each condition wrapped in its own parentheses:
>>> a comfortable range
mild = temps[(temps > 60) & (temps < 85)] print(mild)
Output
[72 65 81]
(temps > 60) & (temps < 85) keeps only the values that satisfy both conditions at once, element by element.
Note: writing
temps > 60 and temps < 85 with Python's own and raises ValueError: truth value of an array with more than one element is ambiguous. Python's and/or expect a single boolean, not an array of them — NumPy's & and | exist specifically to work element-wise instead. The parentheses around each condition aren't optional either: without them, Python tries to evaluate & before > and raises an error.