Sub topic 12
Conditional selection with np.where
This chapter assumes you know boolean masks, elementwise comparisons, and the broadcasting rules from earlier chapters. np.where combines them into a vectorized if/else.
The three-argument form
np.where(condition, x, y) returns an array. Wherever condition is True, the result takes the value from x. Wherever it is False, the result takes the value from y.
import numpy as np
a = np.arange(10)
print(np.where(a > 5, a, 0)) # [0 0 0 0 0 0 6 7 8 9]The comparison a > 5 builds a boolean array of the same shape as a. np.where then picks elementwise between a and the scalar 0. A Python loop with an if would do the same work more slowly.
A boolean mask index such as a[a > 5] is different. It drops the elements that fail the test and returns a shorter copy. np.where keeps the shape and replaces the failing elements.
Broadcasting applies to all three arguments
condition, x, and y are broadcast against each other. The scalar 0 above is the simplest case. You can also pass arrays of different shapes, as long as they follow the broadcasting rules.
import numpy as np
x = np.array([[1.0, -2.0, 3.0],
[-4.0, 5.0, 6.0]])
fill = np.array([[0.0],
[10.0]]) # shape (2, 1)
print(np.where(x < 0, fill, x))
# [[ 1. 0. 3.]
# [10. 5. 6.]]The fill array has shape (2, 1). It stretches across the columns, so each row gets its own replacement value for negative entries.
Strings work too, and the result dtype is the common type of x and y:
import numpy as np
scores = np.array([[55, 82, 71],
[90, 40, 68]])
print(np.where(scores >= 60, "pass", "fail"))
# [['fail' 'pass' 'pass']
# ['pass' 'fail' 'pass']]The one-argument form
Called with only a condition, np.where(condition) returns the positions of the True entries. It gives one index array per axis, packed in a tuple.
import numpy as np
a = np.arange(10)
print(np.where(a % 3 == 0)) # (array([0, 3, 6, 9]),)This form is the same as np.nonzero(condition). In new code, prefer np.nonzero when you only want indices. That keeps the two behaviors of np.where from being confused.
Both branches are always computed
np.where is a function, not a control-flow statement. NumPy evaluates x and y completely before it chooses between them. A branch you meant to skip can still raise warnings or produce nan and inf in the discarded entries.
import numpy as np
a = np.array([0.0, 2.0, 4.0])
with np.errstate(divide="ignore"):
print(np.where(a != 0, 1 / a, 0.0)) # [0. 0.5 0.25]Without np.errstate, 1 / a emits a divide-by-zero warning even though the result for that position is discarded. The output is correct either way. The warning is a side effect of the unused branch.
Common mistakes
- Using
andororin the condition. Use&,|and~, and put each comparison in parentheses, as innp.where((a > 2) & (a < 8), a, 0). - Expecting
np.where(cond, x)to work. With two arguments it raises aValueError. Give either one argument or all three. - Ignoring dtype promotion. Mixing an integer array with
0.5produces a float result.
Exercise
Given a = np.array([3, -1, 4, -1, 5]), write one expression that returns an array where every negative value is replaced by 0 and other values are kept. What does it return?
Show answer
np.where(a < 0, 0, a) returns [3 0 4 0 5]. The condition is True at the negative positions, so those take the value 0. All other positions take the original value from a.