Sub topic 8
Modifying values through masks and np.where
This chapter assumes you can build a boolean mask from a comparison and combine masks with &, |, and ~. Here you will use masks to change data, and np.where to build a new array from a condition.
Assigning through a mask
A boolean mask can sit on the left side of an assignment. NumPy then writes only to the positions where the mask is True.
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]This changes data in place. It works on arrays of any dimension. A full-shape mask on a 2-D array selects individual cells:
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]]Scalars, arrays, and augmented assignment
The right-hand side can be a scalar or an array. A scalar is broadcast to every selected position. An array must have exactly as many elements as the mask has True values, or be broadcastable to that count. Otherwise NumPy raises a ValueError.
import numpy as np
scores = np.array([55, 82, 91, 47, 70])
scores[scores < 60] = [60, 61] # two values for two selected positions
print(scores) # [60 82 91 61 70]
scores[scores > 90] -= 1 # augmented assignment works too
print(scores) # [60 82 90 61 70]np.where: a new array from a condition
np.where(condition, x, y) returns a new array. At each position it takes the value from x where the 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])
clipped = np.where(data > 0, data, 0)
print(clipped) # [4 0 7 0 0 2]
print(data) # [ 4 -1 7 0 -5 2]The arguments x and y can be scalars or arrays. They are broadcast against the condition, so np.where(mask, a, b) also works when a and b are full arrays.
With only the condition, np.where returns a tuple of index arrays, one per axis. You can use these as positions.
import numpy as np
data = np.array([4, -1, 7, 0, -5, 2])
print(np.where(data > 0)) # (array([0, 2, 5]),)Choosing between the two
| Goal | Tool | Original changed? |
|---|---|---|
| Overwrite selected values in place | `a[mask] = value` | Yes |
| Build a result and keep the input | `np.where(mask, x, y)` | No |
| Find the positions that match | `np.where(mask)` | No |
A common error: chained indexing
Indexing with a mask returns a copy, as you saw in the views and copies chapter. If you index again and assign, you write into that temporary copy, and the original stays the same.
import numpy as np
a = np.array([1, 2, 3, 4])
a[a > 2][0] = 99 # modifies a temporary copy
print(a) # [1 2 3 4]
idx = np.where(a > 2)[0]
a[idx[0]] = 99 # one assignment on a itself
print(a) # [ 1 2 99 4]The rule is to do the selection and the assignment in a single indexing expression on the left side. If you need "the first match", compute its position first, as above.
Summary of habits
- Use
a[mask] = valuewhen you want the array itself updated. - Use
np.wherewhen you want a new array and an untouched original. - Check that the number of assigned values matches the number of
Trueentries, or use a scalar. - Never assign through two chained index operations when the first one is a mask or an index array.
Exercise
Given temps = np.array([18.5, 31.0, 25.2, 35.8, 12.1]), write one expression that returns a new array where every value above 30 is replaced by 30, leaving temps unchanged. What does it return?
Show answer
np.where(temps > 30, 30, temps) returns array([18.5, 30. , 25.2, 30. , 12.1]). Because np.where builds a new array, temps keeps its original values.
Exercise
Why does b = np.array([5, 6, 7, 8]); b[b > 5][1] = 0 leave b unchanged, and how do you set the second element that is greater than 5 to 0?
Show answer
b[b > 5] returns a copy, so the second index assigns into that copy. Find the position first: idx = np.where(b > 5)[0]; b[idx[1]] = 0. This gives [5 6 0 8].