Boolean masks

Comparisons, combining with & | ~, np.nonzero, and np.clip.

A comparison on an array returns an array of True / False with the same shape. Use it to pick values or to find positions.

Goal

Filter a units grid with comparisons, combine masks with & | ~, and read np.nonzero.

Compare, then index

# Rows: Nairobi, Mombasa, Kisumu  ·  cols: A, B, C
units = np.array(
    [
        [12, 7, 2],
        [9, 6, 0],
        [3, 11, 1],
    ],
    dtype=float,
)
busy = units >= 9
print(busy)
print()
print(units[busy])

units[busy] is 1-D — every True cell, in memory order.

Combine with & | ~

units = np.array(
    [
        [12, 7, 2],
        [9, 6, 0],
        [3, 11, 1],
    ],
    dtype=float,
)
mid = (units >= 3) & (units < 10)
print(mid)
print(units[mid])
print()
print("quiet (not busy):")
print(units[~(units >= 9)])

Parentheses are required. units >= 3 & units < 10 is a bitwise accident.

Positions with nonzero

units = np.array(
    [
        [12, 7, 2],
        [9, 6, 0],
        [3, 11, 1],
    ],
    dtype=float,
)
rows, cols = np.nonzero(units >= 9)
print("rows:", rows)
print("cols:", cols)
print("values:", units[rows, cols])

Nairobi A, Mombasa A, Kisumu B.

np.clip

units = np.array(
    [
        [12, 7, 2],
        [9, 6, 0],
        [3, 11, 1],
    ],
    dtype=float,
)
print(np.clip(units, 1, 10))

Values below 1 become 1; above 10 become 10. Zeros in the grid become 1 here.

Pitfall

Python’s and / or do not work on arrays. Use & / | / ~ and wrap each comparison in parentheses.