Sub topic 12
Conditional Selection with np.where
np.where is NumPy's vectorized if/else. It picks values from one of two sources for every element, based on a condition, and it does so without a Python loop. This chapter covers its two call forms, how broadcasting applies to it, how the result dtype is chosen, and the mistakes that cause warnings or wrong output.
This chapter assumes you know how boolean masks work (an array of True and False built from a comparison) and the broadcasting rules for combining shapes.
The three-argument form
The call np.where(condition, x, y) returns an array. At each position, the result takes the value from x where condition is True and from y where it is False.
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 produces a boolean array of shape (10,). The values from a are kept where the mask is True. The scalar 0 fills everything else. The result has the same shape as the mask, not a shorter one.
That is the main difference from boolean-mask indexing:
| Expression | Result shape | What it does |
|---|---|---|
| `a[a > 5]` | 1-D, only the selected items | Filters: drops elements |
| `np.where(a > 5, a, 0)` | Same as the broadcast of the inputs | Replaces: keeps every position |
Use a mask index when you want fewer elements. Use np.where when you want every position to stay and some values to change.
Broadcasting applies to all three arguments
condition, x and y do not need matching shapes. NumPy broadcasts all three to a common shape using the usual rules. Scalars are the simplest case, as in the 0 above. Strings work the same way:
import numpy as np
a = np.arange(5)
print(np.where(a % 2 == 0, "even", "odd"))
# ['even' 'odd' 'even' 'odd' 'even']A condition of shape (3, 1) can select whole rows of a (3, 4) array. The np.newaxis index adds the size-1 axis.
import numpy as np
m = np.arange(12).reshape(3, 4)
keep_row = np.array([True, False, True])[:, np.newaxis] # shape (3, 1)
print(np.where(keep_row, m, -1))
# [[ 0 1 2 3]
# [-1 -1 -1 -1]
# [ 8 9 10 11]]The mask has shape (3, 1), m has shape (3, 4), and -1 is a scalar. The common shape is (3, 4). If the shapes cannot be broadcast together, you get the same ValueError as with arithmetic.
How the result dtype is chosen
The result dtype is the common type of x and y, found by NumPy's usual type promotion. The condition does not affect it.
import numpy as np
a = np.arange(10)
print(np.where(a > 5, a, 0).dtype) # int64 on most platforms
print(np.where(a > 5, a, 0.5).dtype) # float64One float among the two sources turns the whole result into floats. This matters when you use np.nan as a filler, because np.nan is a float. An integer array filled with np.nan through np.where comes back as float64. Integer arrays have no way to store a missing value.
A common cleaning idiom replaces nan values:
import numpy as np
x = np.array([1.0, np.nan, 3.0])
print(np.where(np.isnan(x), 0.0, x)) # [1. 0. 3.]The one-argument form: finding positions
With only the condition, np.where(condition) returns the indices where the condition is True. It is the same as np.nonzero(condition). The result is a tuple with one index array per dimension of the input.
import numpy as np
b = np.array([3, 8, 1, 9, 4])
idx = np.where(b > 3)
print(idx) # (array([1, 3, 4]),)
print(idx[0]) # [1 3 4]
m = np.array([[1, 5],
[7, 2]])
rows, cols = np.where(m > 4)
print(rows) # [0 1]
print(cols) # [1 0]For a 1-D input you still get a tuple, so you must take element [0]. For a 2-D input the tuple holds a row array and a column array. They pair up by position: the first match is at (rows[0], cols[0]), which is (0, 1). The tuple can be used directly as an index, so m[np.where(m > 4)] returns [5 7]. That is equivalent to m[m > 4].
Passing exactly two arguments is an error. NumPy raises a ValueError saying that either both or neither of x and y should be given.
Both branches are always computed
np.where is a function, not a control-flow statement. Python evaluates x and y fully before the function runs. Every element of both branches is computed, even the ones that will be thrown away.
This is a trap when one branch is invalid for some inputs:
import numpy as np
x = np.array([4.0, 0.0, 2.0])
with np.errstate(divide="ignore"):
result = np.where(x != 0, 1 / x, 0.0)
print(result) # [0.25 0. 0.5 ]The expression 1 / x divides by zero at the second position and produces inf. The where then discards it, so the final answer is correct. Without the errstate block, NumPy would still print a RuntimeWarning: divide by zero. The answer is right, but the warning is real noise. A worse case arises when the discarded branch raises an exception. Integer division by zero in some operations, or an index that is out of range, fails before np.where is even called.
The where argument of ufuncs avoids the problem. A ufunc is a universal function such as np.divide. It computes only the positions where the mask is True and leaves other positions untouched in out:
import numpy as np
x = np.array([4.0, 0.0, 2.0])
safe = np.divide(1.0, x, out=np.zeros_like(x), where=x != 0)
print(safe) # [0.25 0. 0.5 ]Here out is pre-filled with zeros. Division runs only where x != 0, so no warning is raised. Always supply out when you use where with a ufunc. Positions that are not computed keep whatever was in the output buffer. If the buffer comes from np.empty, those values are random garbage.
Combining conditions
Conditions combine with the elementwise operators & (and), | (or) and ~ (not). Python's and, or and not do not work on arrays with more than one element. They raise a ValueError about the truth value being ambiguous.
Operator precedence is the second trap. & binds more tightly than comparison operators, so each comparison needs its own parentheses:
import numpy as np
a = np.arange(10)
print(np.where((a > 2) & (a < 7), a, 0)) # [0 0 0 3 4 5 6 0 0 0]Writing a > 2 & a < 7 fails. Python reads it as the chained comparison a > (2 & a) < 7, which ends in the same ambiguity error.
More than two outcomes
For three or more outcomes you can nest calls, as in np.where(c1, A, np.where(c2, B, C)). That gets hard to read quickly. np.select handles many cases in a flat list. It takes a list of conditions and a list of matching values, and the first true condition wins at each position:
import numpy as np
scores = np.array([95, 82, 67, 40])
grade = np.select(
[scores >= 90, scores >= 80, scores >= 60],
[4, 3, 2],
default=0,
)
print(grade) # [4 3 2 0]The score 95 satisfies all three conditions, but only the first one counts. Order the conditions from most specific to least specific. Positions where no condition is true get default, which is 0 if you leave it out.
Common mistakes
- Expecting a filter.
np.where(mask, a, 0)keeps the full shape. If you need only the matching items, index witha[mask]. - Forgetting the tuple. The one-argument form returns a tuple of arrays, even for 1-D input.
- Unwanted dtype changes. A float filler such as
np.nanor0.5converts an integer result to float. Choose the filler to match the dtype you want to keep. - Warnings from the unused branch. Both branches always run. Guard invalid operations with
np.errstateor a ufuncwhere=. - Missing parentheses or Python keywords. Use
&,|and~, with each comparison in parentheses. - Accidental broadcasting. A condition of shape
(3,)against values of shape(3, 3)broadcasts along the last axis, which may not be the axis you meant. Print.shapeof all three inputs when a result looks wrong.
Exercise
The array x = np.array([[1.0, -2.0], [-3.0, 4.0]]) contains some negative numbers. Write one np.where expression that returns an array of the same shape with each negative value replaced by 0.0 and the other values unchanged. What are the result and its dtype?
Show answer
np.where(x < 0, 0.0, x). The result is [[1., 0.], [0., 4.]] with shape (2, 2) and dtype float64. The condition has shape (2, 2), the scalar 0.0 broadcasts, and x supplies the unchanged values.
Exercise
A student writes np.where(x > 0, np.log(x), 0.0) for x = np.array([1.0, 0.0, np.e]). The output values are correct, but NumPy prints a RuntimeWarning. Why does this happen, and how can you compute the same result without the warning?
Show answer
np.where evaluates np.log(x) for every element before choosing, including the zero, where log gives -inf and warns about divide by zero. The where call then discards that value, so the result [0. 0. 1.] is right. To avoid the warning, use np.log(x, out=np.zeros_like(x), where=x > 0), which computes the log only where x > 0 and leaves 0.0 elsewhere.