Boolean Indexing (NumPy)
Boolean indexing filters a NumPy array by passing it a boolean mask of the same shape, keeping only the elements where the mask is True. It is the standard way to select array elements that meet a condition.
NumPy
A comparison on an array — a > 20 — produces a boolean array of the same shape, and feeding that back in with a[a > 20] returns just the matching elements as a flat array. This is how you filter data without writing a loop.
Combine conditions with the bitwise operators & (and), | (or), and ~ (not), wrapping each in parentheses because of operator precedence; the Python keywords and/or do not work on arrays. The mask also works for assignment: a[a < 0] = 0 clamps negatives to zero in place.
Because it gathers an arbitrary subset, boolean indexing returns a copy rather than a view. For choosing between two values per element based on a condition, np.where is the companion tool.
Syntax
a[a > value] | a[(cond1) & (cond2)]Examples
Python
import numpy as np
a = np.array([10, 20, 30, 40])
print(a[a > 20])Output:
[30 40]