Boolean and Fancy Indexing
Python · NumPy Library
Theory
A comparison on an array returns a boolean array of the same shape: marks >= 60 gives [False, True, True, ...]. Passing that mask back in, marks[marks >= 60], keeps only the positions that are True. Combine conditions with & (and), | (or) and ~ (not), wrapping each one in parentheses: marks[(marks >= 60) & (marks < 90)]. Python's and/or keywords do not work on arrays.
Fancy indexing passes a list of positions instead: marks[[0, 3, 5]] returns those three values in that order, and repeats are allowed. Both styles also work for assignment, so marks[marks < 40] = 40 raises every failing mark to 40 in place. Unlike slices, boolean and fancy indexing return a copy, and on a 2-D array a boolean mask of the same shape returns a flat 1-D result.
Why we use it
Filtering by a condition is the most common data task: passing students, orders above a value, readings out of range. Boolean masks do it for the whole array at once and are the same idea pandas uses for df[df['col'] > x].
When to use it
Use a mask when the selection depends on the values, fancy indexing when you have a list of positions (for example from argsort). Use np.where(cond, a, b) instead when you want to keep every element and choose between two values.
How it works
- Array of values
- Write a condition: marks >= 60
- NumPy returns a True/False mask of the same shape
- More than one condition? Yes: Combine with & | ~ and parentheses. No: Use the single mask.
- arr[mask] keeps only the True positions
- Filtered copy (or arr[mask] = x to edit)
Syntax
mask = arr > value
arr[mask]
arr[(cond1) & (cond2)] arr[(c1) | (c2)] arr[~cond]
arr[[i, j, k]]
arr[mask] = new_valueExample
marks = np.array([45, 82, 67, 91])
print(marks[marks >= 60]) # [82 67 91]
print(marks[[0, 3]]) # [45 91]Key points
- Wrap each condition in parentheses when using & and |
- Use &, |, ~ on arrays; Python's and / or raise an error
- mask.sum() counts True values; mask.mean() gives the share
- Boolean and fancy indexing return copies, not views
- arr[mask] = value edits the original array in place