Sub topic 5
Conditional columns with numpy.where and numpy.select
This chapter replaces if/elif/else logic inside row loops with two NumPy functions that work on whole columns. It assumes you can build a DataFrame, read a boolean expression such as df["qty"] >= 3, and know that a Series has an index. Earlier chapters covered column arithmetic and boolean masks. Here we use masks to choose values.
The loop being replaced
A common first attempt at a conditional column walks the rows and appends one value per row:
import numpy as np
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 15.0], "qty": [3, 1, 4]})
df["total"] = df["price"] * df["qty"]
sizes = []
for _, row in df.iterrows():
if row["qty"] >= 3:
sizes.append("bulk")
else:
sizes.append("single")
df["size_loop"] = sizesEach pass through the loop builds a Series for the row, runs Python bytecode, and appends to a list. The condition is a plain comparison, so pandas can evaluate it for every row at once as a boolean mask. numpy.where then picks between two outcomes using that mask.
Two-way choices with numpy.where
numpy.where(condition, value_if_true, value_if_false) returns an array. For each position, it takes the second argument where the condition is True and the third where it is False.
df["size"] = np.where(df["qty"] >= 3, "bulk", "single")
print(df["size"].equals(df["size_loop"]))The output is True: the one-line version matches the loop.
The two outcome arguments do not have to be scalars. They can be columns or expressions, and NumPy picks element by element:
df["discounted"] = np.where(df["qty"] >= 3, df["total"] * 0.9, df["total"])Rows with qty >= 3 get a 10% discount and the others keep their total. The three arguments are broadcast against each other, so any mix of scalars and equal-length columns works.
Nested where calls
For three outcomes you can nest calls:
df["band_nested"] = np.where(
df["total"] < 40, "low", np.where(df["total"] < 60, "mid", "high")
)This works, but it gets hard to read at three or four levels. Use numpy.select for those cases.
Several outcomes with numpy.select
numpy.select(condlist, choicelist, default) takes a list of boolean masks and a list of matching outcomes. For each row it uses the outcome of the first condition that is true. If no condition is true, it uses default.
conditions = [df["total"] < 40, df["total"] < 60]
df["band"] = np.select(conditions, ["low", "mid"], default="high")With totals of 30, 20 and 60, the bands are low, low and high. The structure maps directly onto an if/elif/else chain: conditions in order, then the else as default.
In NumPy this is not a loop over rows. Every condition is computed for the whole column, and the results are then combined.
Order decides the result
The first matching condition wins, exactly as in an elif chain. Both conditions below are true for a total of 30, so reversing the order changes the output:
wrong = np.select([df["total"] < 60, df["total"] < 40], ["mid", "low"], default="high")
print(wrong)This prints ['mid' 'mid' 'high']. The low choice is never reached, because every total below 40 is also below 60. Put the most specific condition first, just as you would in the loop.
Always pass default
If you leave out default, it is the integer 0. That does not fit string choices, and with numeric choices it silently puts a 0 in unmatched rows. State the fallback explicitly. For numeric output where "no match" should be missing, use default=np.nan. The result is then a float array.
Verifying against the loop
A rewrite is only useful if it gives the same answer. Keep the loop version around as a reference and compare:
def band_loop(frame):
out = []
for _, row in frame.iterrows():
if row["total"] < 40:
out.append("low")
elif row["total"] < 60:
out.append("mid")
else:
out.append("high")
return pd.Series(out, index=frame.index)
vectorised = pd.Series(
np.select(conditions, ["low", "mid"], default="high"), index=df.index
)
assert vectorised.equals(band_loop(df))The assertion passes silently when the two agree. Run it on data that includes edge values, such as a total of exactly 40 or exactly 60. Off-by-one errors in < versus <= usually show up there.
Edge cases
Missing values fall through
Any comparison with NaN is False. A missing value therefore fails every condition and lands in the "else" branch, which is often wrong:
scores = pd.DataFrame({"score": [82.0, np.nan, 45.0, 67.0]})
scores["naive"] = np.where(scores["score"] >= 50, "pass", "fail")
print(scores["naive"].tolist())This prints ['pass', 'fail', 'fail', 'pass']. The missing score was labelled fail. Test for missing values first, using numpy.select:
conditions = [scores["score"].isna(), scores["score"] >= 50]
scores["result"] = np.select(conditions, ["missing", "pass"], default="fail")
print(scores["result"].tolist())This prints ['pass', 'missing', 'fail', 'pass'].
Both branches are always computed
numpy.where evaluates both outcome expressions for every row before choosing. It does not skip the "false" branch where the condition is false. This matters when the unused branch would fail or produce garbage:
inv = pd.DataFrame({"revenue": [100.0, 50.0, 80.0], "units": [4, 0, 8]})
inv["unit_price"] = np.where(
inv["units"] > 0, inv["revenue"] / inv["units"], np.nan
)The division for the row with zero units is still computed. With pandas Series it produces inf, which where then discards. With bare NumPy arrays the same division would emit a RuntimeWarning. The result is correct either way. The risk is an outcome expression that raises an exception, or one that is very expensive, because it runs for all rows.
The result is an array, not a Series
numpy.where and numpy.select return plain NumPy arrays with no index. Assigning one to a column of the same DataFrame is safe, because the values go in by position and the lengths must match. If you build a separate Series from the result, pass the index explicitly, as band_loop and the check above do. Otherwise the new Series gets a default 0..n-1 index, and it can misalign with a frame that was filtered or re-indexed earlier.
One-argument where is a different function
np.where(mask) with a single argument does not choose values. It returns the integer positions where the mask is true, as a tuple of arrays. If you see a tuple where you expected a column, check that you passed all three arguments.
Mixed outcome types
All outcomes are combined into one dtype. Mixing numbers and strings produces strings or objects, not a column of mixed types that still supports arithmetic. Keep each conditional column to one kind of value. If you need both a label and a number, make two columns from the same masks.
Pandas alternatives
NumPy is not the only tool for conditional values. These pandas methods suit narrower cases:
| Task | Tool | Example |
|---|---|---|
| Change only the values that fail a test, keep the rest | `Series.where` or `Series.mask` | `df["total"].where(df["total"] <= 50, 50)` |
| Cap or floor numbers | `Series.clip` | `df["total"].clip(upper=50)` |
| Label numeric ranges | `pd.cut` | `pd.cut(df["total"], [-np.inf, 40, 60, np.inf], labels=["low", "mid", "high"], right=False)` |
Series.where(cond, other) keeps the original value where cond is true and uses other elsewhere. mask does the opposite. They are shorter than numpy.where when one of the outcomes is the existing column. pd.cut suits ranges of one numeric column. It returns a categorical column, and with right=False each bin includes its left edge, which matches the < conditions used earlier. numpy.select is the general tool when conditions involve different columns or are not simple ranges.
Choosing between them
- Two outcomes: use
numpy.where. - Three or more outcomes, or conditions on several columns: use
numpy.select, with the most specific condition first and an explicitdefault. - Changing some values in an existing column: use
where,maskor a boolean-mask assignment. - Numeric ranges: use
pd.cutif you want a categorical result, ornumpy.selectif you want plain values.
Exercise
A DataFrame has a numeric column temp. You write np.select([df["temp"] > 20, df["temp"] > 30], ["warm", "hot"], default="cold"). A row has temp = 35. What label does it receive, and how do you fix the code so that 35 is labelled hot?
Show answer
It receives warm. Both conditions are true for 35, and np.select uses the first true condition, which is > 20. Put the more specific condition first: np.select([df["temp"] > 30, df["temp"] > 20], ["hot", "warm"], default="cold").
Exercise
A column grade contains [91.0, np.nan, 58.0]. Write a np.select call that returns "A" for 90 or above, "pass" for 60 or above, "missing" for NaN, and "fail" otherwise, and give the result for each row.
Show answer
np.select([df["grade"].isna(), df["grade"] >= 90, df["grade"] >= 60], ["missing", "A", "pass"], default="fail"). The result is ["A", "missing", "fail"]. The isna() test can go anywhere before the default, because NaN >= 90 and NaN >= 60 are both false. Placing it first makes the intent clear.
Exercise
You compute np.where(units > 0, revenue / units, np.nan) on plain NumPy arrays and see a RuntimeWarning about division by zero, but the output is correct. Why does the warning appear even though the zero-unit rows end up as NaN?
Show answer
np.where evaluates both outcome expressions for every row before it applies the condition. The division revenue / units therefore runs on the zero-unit rows too, which triggers the warning. The condition then discards that result and uses np.nan for those rows.