Sub topic 8
Modifying values through masks and np.where
This chapter assumes you can build arrays with np.array, np.arange, and reshape, and that you know what shape and dtype mean. It also assumes you have seen how a comparison such as data > 0 produces a boolean mask. Here you use masks to change values, and you use np.where to build new arrays from a condition.
Assignment through a mask
A mask on the left side of = is a write operation. NumPy finds every position where the mask is True and stores the new value there. The array changes in place.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
data[data < 0] = 0
print(data) # [4 0 7 0 0 2]The mask data < 0 is computed first, then used as the target. The same pattern works in any number of dimensions.
import numpy as np
a = np.arange(12).reshape(3, 4)
a[a % 2 == 0] = 0
print(a)
# [[ 0 1 0 3]
# [ 0 5 0 7]
# [ 0 9 0 11]]The right side can be a scalar or an array. A scalar is broadcast to every selected position. An array must supply exactly one value per True in the mask, in the order NumPy visits the elements (row-major order).
import numpy as np
a = np.array([10, 20, 30, 40, 50])
a[a > 25] = [1, 2, 3]
print(a) # [10 20 1 2 3]
b = np.array([10, 20, 30, 40, 50])
b[b > 25] = [1, 2] # ValueError: 3 positions selected, 2 values givenThe error comes from a count mismatch. A length-1 array or a scalar is always allowed, because it broadcasts.
Updating with an operator
a[mask] += 5 is shorthand for reading the selected elements, adding 5, and writing them back to the same positions.
import numpy as np
scores = np.array([55, 82, 91, 67, 74])
scores[scores < 70] += 5
print(scores) # [60 82 91 72 74]Only the two scores below 70 change. This is the usual way to apply a transformation to a subset of an array without a loop.
Assigning through a view
If the array you index is a view, the write reaches the original array. Chapter 5 covered why: a basic slice shares memory with its base.
import numpy as np
a = np.arange(12).reshape(3, 4)
left = a[:, :2]
left[left > 4] = -1
print(a)
# [[ 0 1 2 3]
# [ 4 -1 6 7]
# [-1 -1 10 11]]The mask was built from left, which has shape (3, 2). The write landed in a because left is a view of it. If you want to change only a separate result, call .copy() before assigning.
The dtype of the target decides the result
Assignment never changes the array's dtype. NumPy casts the new values to the existing dtype, and this can silently lose information.
import numpy as np
ints = np.array([1, 2, 3, 4])
ints[ints > 2] = 9.7
print(ints) # [1 2 9 9], 9.7 was truncated to 9If you need fractional results, convert first with ints.astype(float), or use np.where, which picks the result dtype from its inputs.
Missing values: a special case
A common use of mask assignment is cleaning data. NaN (not a number) is never equal to anything, including itself. So a mask built with == np.nan is always all False. Use np.isnan instead.
import numpy as np
x = np.array([1.0, np.nan, 3.0, np.nan])
print(x == np.nan) # [False False False False]
x[np.isnan(x)] = 0.0
print(x) # [1. 0. 3. 0.]Building new arrays with np.where
np.where(condition, x, y) returns a new array. At each position it takes the value from x where condition is True and from y where it is False. The original array is not touched.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
print(np.where(data > 0, data, -1)) # [ 4 -1 7 -1 -1 2]
print(data) # [ 4 -1 7 0 -5 2], unchangedHere is a case where the two branches are different types of value.
import numpy as np
temps = np.array([18.5, 25.1, 30.2, 12.0, 22.8])
labels = np.where(temps > 24, "hot", "mild")
print(labels) # ['mild' 'hot' 'hot' 'mild' 'mild']All three arguments broadcast against each other. That makes it easy to mix an array with a scalar, or a 2-D array with a row.
import numpy as np
a = np.arange(6).reshape(2, 3)
print(np.where(a % 2 == 0, a, -a))
# [[ 0 -1 2]
# [-3 4 -5]]Choosing between mask assignment and np.where
The two tools overlap, and the main difference is whether you want to mutate or to produce a new array.
| Need | Tool | Changes the original? |
|---|---|---|
| Overwrite values in place | `a[mask] = value` | Yes |
| Apply an operation to a subset in place | `a[mask] += value` | Yes |
| Create a result with two alternatives | `np.where(mask, x, y)` | No |
| Keep the original and also edit | `b = a.copy(); b[mask] = value` | Only `b` |
Three or more outcomes: np.select
Nested np.where calls work but become hard to read. np.select takes a list of conditions and a list of matching results. The first condition that is True at a position wins, and default covers positions where none match.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
sign = np.select([data < 0, data == 0], [-1, 0], default=1)
print(sign) # [ 1 -1 1 0 -1 1]The one-argument form of np.where
Called with only a condition, np.where returns the positions of the True values, not a new array. The result is a tuple with one index array per dimension.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
idx = np.where(data > 0)
print(idx) # (array([0, 2, 5]),)
print(data[idx]) # [4 7 2]This is equivalent to np.nonzero(data > 0). For a 1-D array, np.flatnonzero gives you the plain index array without the tuple, which is handy for the next section.
A pitfall: chained indexing writes to a copy
Boolean-mask indexing returns a copy, not a view. So this looks reasonable but does nothing:
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
a[a > 3][0] = 100 # no error, but a is unchanged
print(a) # [1 2 3 4 5 6]Python runs this as two separate operations. First a[a > 3] is evaluated, which creates a temporary copy [4, 5, 6]. Then [0] = 100 writes into that copy, which is thrown away. A single a[mask] = value is different, because it is one call and NumPy writes straight into a.
To change a specific one of the selected elements, convert the mask to indices and index a once:
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
idx = np.flatnonzero(a > 3) # array([3, 4, 5])
a[idx[0]] = 100
print(a) # [ 1 2 3 100 5 6]Compare this with a[2:][0] = 100, which does work, because a basic slice is a view. The rule of thumb: a write must reach the original array in the last indexing step, and every earlier step must be a basic slice.
Both branches of np.where are always computed
np.where is a function, so Python evaluates x and y fully before the function runs. The condition only selects results. It does not skip computation, so an expression that fails or warns on some elements will still do so.
import numpy as np
vals = np.array([4.0, 0.0, 16.0])
result = np.where(vals > 0, 1 / vals, 0) # RuntimeWarning: divide by zero
print(result) # [0.25 0. 0.0625]The values are right, but the warning shows that 1 / 0.0 was still computed. When the unwanted branch is an error or a warning, use a ufunc's where= and out= arguments. They skip the masked positions entirely.
import numpy as np
vals = np.array([4.0, 0.0, 16.0])
result = np.divide(1, vals, out=np.zeros_like(vals), where=vals > 0)
print(result) # [0.25 0. 0.0625]Positions where where is False keep whatever out already contained, which is why out is pre-filled with zeros.
Summary of rules
a[mask] = valuewrites in place, and the right side must be a scalar or have exactly one value perTrue.- The target dtype is fixed, so assigned values are cast, and floats assigned into an integer array are truncated.
np.where(cond, x, y)returns a new array and leaves the input alone.np.where(cond)returns index arrays, equal tonp.nonzero(cond).- Mask indexing on the right side returns a copy, so
a[mask][i] = vnever changesa. - Both branches of
np.whereare always evaluated.
Exercise
Given a = np.array([3, 8, 1, 9, 4]), write code that (1) sets every element greater than 5 to 5 in place, and (2) separately, without changing a afterwards, produces an array in which elements below 4 are replaced by 0. What are a and the second array?
Show answer
Step 1: a[a > 5] = 5 gives a = [3 5 1 5 4]. Step 2: b = np.where(a < 4, 0, a) gives b = [0 5 0 5 4], and a is still [3 5 1 5 4] because np.where returns a new array. (np.clip(a, None, 5) would also do step 1, but returns a new array.)
Exercise
A learner writes x = np.array([2, 5, 7, 9]); x[x > 4][1] = 0 and expects [2 5 0 9]. What does x contain afterwards, why, and what is a correct way to get the intended result?
Show answer
x is unchanged, [2 5 7 9]. The expression x[x > 4] is a boolean-mask selection, which returns a copy, and [1] = 0 writes into that temporary copy. A correct version is idx = np.flatnonzero(x > 4); x[idx[1]] = 0, which gives [2 5 0 9].