You can write into a slice (a view) or build a new array with np.where. In-place updates are fast; expressions are easier to reread.
Goal
Overwrite a row or a mask, fill a block, and use np.where as an expression.
Write a row
# Rows: Nairobi, Mombasa, Kisumu · cols: A, B, C
units = np.array(
[
[12, 7, 2],
[9, 6, 0],
[3, 11, 1],
],
dtype=float,
)
units[2] = [4, 4, 4]
print(units)Kisumu is now 4, 4, 4. That assignment used the view of row 2.
Write where a mask is True
units = np.array(
[
[12, 7, 2],
[9, 6, 0],
[3, 11, 1],
],
dtype=float,
)
units[units == 0] = np.nan
print(units)Integer arrays cannot hold nan — this grid is float, so the zeros become missing. The Types chapter covers the cast.
np.where as an expression
units = np.array(
[
[12, 7, 2],
[9, 6, 0],
[3, 11, 1],
],
dtype=float,
)
out = np.where(units >= 9, units, 0)
print(out)Busy cells keep their units; the rest become 0. units itself is unchanged.
fill
buf = np.empty((2, 3))
buf.fill(10.5)
print(buf)empty does not zero the buffer — fill (or zeros / full) makes the contents defined.
Tip
Prefer out = np.where(...) when you want to keep the original. Prefer arr[mask] = value when you mean to edit in place.