Sahaj.blogs
12 Feb 2024 · StudyPhase 3 · NumPy

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 > 5 gives an array of True/False, and a[mask] keeps the True positions. Combine conditions with &, | and ~, with parentheses, because and and or don’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 from x or y, 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 positions

#numpy#indexing

Sources

  1. Indexing: boolean array indexing — NumPy
  2. Indexing: integer array indexing — NumPy
  3. numpy.where — NumPy