typestar

Boolean masks in Python

A boolean array selects, counts and assigns in one expression.

import numpy as np

values = np.array([5, 12, 7, 20, 3])
big = values > 8

print(big, big.sum())
print(values[big])
print(np.where(big, values, 0))

values[values < 5] = 0
print(values)
print(np.any(big), np.all(big))

How it works

  1. A comparison gives a mask of the same shape.
  2. sum on a mask counts the True values.
  3. Assigning through a mask writes only where it is True.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
217
Tokens
85
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 49 seconds.

Type this snippet

Step 1 of 3 in Indexing, step 13 of 22 in NumPy.

← Previous Next →