NumPy · Boolean and fancy indexing
Selecting with boolean masks and integer arrays, combining conditions with & and |, np.where, and why these return copies.
Two more ways to index, and both return copies rather than views:
- Boolean mask:
a > 5gives an array ofTrue/False, anda[mask]keeps theTruepositions. Combine conditions with&,|and~, with parentheses, becauseandandordon’t work element-wise. - Fancy indexing: pass an array of integer positions, e.g.
a[[0, 3, 3]]. np.where(cond, x, y)picks element-wise fromxory, a vectorised if/else.
Assigning through a mask (a[a < 0] = 0) does modify a in place. It’s the selection that makes a copy.
import numpy as np
marks = np.array([88, 35, 72, 91, 40, 55, 28])
passed = marks >= 40
print(passed)
print(marks[passed], passed.sum(), "passed")
print(marks[(marks >= 50) & (marks < 90)])
print(marks[[0, 3, 3]])
grades = np.where(marks >= 85, "A", np.where(marks >= 50, "B", "C"))
print(grades)
clipped = marks.copy()
clipped[clipped < 40] = 40
print(clipped)
print(np.argsort(marks)[::-1][:3], "-> top-3 positions")
Output:
[ True False True True True True False]
[88 72 91 40 55] 5 passed
[88 72 55]
[88 91 91]
['A' 'C' 'B' 'A' 'C' 'B' 'C']
[88 40 72 91 40 55 40]
[3 0 2] -> top-3 positionsSources
- Indexing: boolean array indexing — NumPy
- Indexing: integer array indexing — NumPy
- numpy.where — NumPy