Sub topic 5
Conditional Columns with np.where and np.select
This chapter assumes you can build a DataFrame, select a column by name, and write comparisons such as df["price"] < 5. You should also know that a comparison on a column returns a boolean Series. NumPy knowledge is helpful but not required.
A conditional column takes its value from a rule such as "if the price is under 5, label it low, otherwise label it mid". A Python if statement does not work on a whole column, so pandas code uses vectorized tools. This chapter covers np.where for two outcomes, np.select for many outcomes, and the errors that come up most often.
Why a plain `if` fails
A comparison on a column produces one boolean per row. Python's if expects a single truth value.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp", "desk"],
"price": [1.5, 12.0, 30.0, 150.0],
"qty": [10, 3, 2, 0],
})
try:
if df["price"] < 5:
print("cheap")
except ValueError as err:
print(err)The error says the truth value of a Series is ambiguous. Pandas cannot decide whether you mean "any row" or "all rows". The fix is to compute a result for every row at once.
Two outcomes with np.where
np.where(condition, value_if_true, value_if_false) evaluates the condition for every row. It returns a NumPy array, and you assign that array to a column.
import numpy as np
df["cheap"] = np.where(df["price"] < 5, "yes", "no")
print(df)The three arguments can each be a scalar, a Series, or an array of the same length. Using Series for the outcomes lets you compute different values per branch.
df["discounted"] = np.where(
df["qty"] >= 3,
df["price"] * 0.9,
df["price"],
)
print(df[["item", "price", "qty", "discounted"]])Rows with a quantity of 3 or more get a 10 percent discount. The other rows keep their original price.
Combining conditions
Combine boolean Series with & (and), | (or), and ~ (not). Wrap each comparison in parentheses, because these operators bind more tightly than < or ==.
df["bulk_cheap"] = np.where(
(df["price"] < 20) & (df["qty"] >= 3),
True,
False,
)This particular example is redundant, since the condition is already a boolean. You can write df["bulk_cheap"] = (df["price"] < 20) & (df["qty"] >= 3) and get the same column. Use np.where when the outputs are something other than True and False.
The Python keywords and, or, and not raise the same "truth value is ambiguous" error you saw above. Use the symbols.
Many outcomes with np.select
Nesting np.where calls works, but it gets hard to read after two levels. np.select takes a list of conditions and a matching list of values. For each row it uses the value paired with the first condition that is true. If no condition is true, it uses default.
df["tier"] = np.select(
[df["price"] < 5, df["price"] < 20],
["low", "mid"],
default="high",
)
print(df[["item", "price", "tier"]])The result is low for the pen, mid for the book, and high for the lamp and desk.
Order matters
Conditions are checked in the order you list them, and the first match wins. That is why the second condition above is price < 20 and not 5 <= price < 20. A price of 1.5 also satisfies < 20, but the first condition already claimed it.
If you reverse the list, every row under 20 becomes mid, and low never appears. Put the most specific condition first.
Default values and dtypes
The default is 0 if you leave it out. That is a problem when the other values are strings, because NumPy cannot mix the integer 0 with strings in a way you would want. Always pass default explicitly and make its type match the other values.
To leave unmatched rows missing, use np.nan for numeric outputs or None for text outputs.
df["flag"] = np.select(
[df["qty"] == 0, df["qty"] >= 3],
["out_of_stock", "plenty"],
default=None,
)
print(df[["item", "qty", "flag"]])The book and the pen are plenty, the desk is out_of_stock, and the lamp is missing because neither condition applied.
Conditions and values must line up
The condlist and choicelist must have the same length. Each condition must be a boolean array of the same length as the DataFrame. A mismatch raises a ValueError. Conditions that are plain Python booleans (for example True as a catch-all) are also accepted, which gives you another way to write a default.
Missing values in conditions
A comparison with NaN returns False. This means a missing value silently falls into the else branch of np.where or into the default of np.select.
scores = pd.DataFrame({"score": [90.0, 55.0, np.nan]})
scores["result"] = np.where(scores["score"] >= 60, "pass", "fail")
print(scores)The row with no score is labeled fail, which is probably wrong. Handle missing values as an explicit case, and put that case first.
scores["result"] = np.select(
[scores["score"].isna(), scores["score"] >= 60],
["unknown", "pass"],
default="fail",
)
print(scores)Now the missing score becomes unknown. Checking isna() first matters here for the same ordering reason as before.
Alternatives and when to use them
Pandas offers other ways to build conditional columns. The table compares them.
| Tool | Best for | Notes |
|---|---|---|
| `np.where` | Two outcomes | Returns a NumPy array, so the index is dropped. |
| `np.select` | Three or more outcomes | First true condition wins. Always set `default`. |
| `Series.where(cond, other)` | Keeping values and replacing the rest | Keeps the original index and keeps values where `cond` is true. |
| `Series.mask(cond, other)` | Replacing values where a condition is true | The opposite of `where`. |
| `Series.clip(lower, upper)` | Capping numbers at limits | Simpler than a condition for min and max rules. |
| `apply` with a function | Rules too complex to write as conditions | Slower, because it runs Python code per row. |
The method Series.where is easy to confuse with np.where. They are different. Series.where(cond, other) keeps each value where cond is true and uses other elsewhere.
df["price_capped"] = df["price"].where(df["price"] <= 100, 100)
print(df[["item", "price", "price_capped"]])Here prices above 100 are replaced by 100, and all others stay unchanged. For this exact case, df["price"].clip(upper=100) is shorter.
Index alignment
np.where and np.select return plain arrays, so they ignore the index. They line up with the DataFrame by position, not by label. That is safe when the inputs come from the same DataFrame. It can go wrong if you pass a Series from a different frame or from a filtered, reordered copy, because pandas will not realign it for you.
Assigning the resulting array to df["new"] also requires the array length to equal the number of rows. If you filtered the data and assign an array of a different length, you get a ValueError.
Common errors
- Using
andoror. Use&and|, with parentheses around each comparison. - Forgetting parentheses.
df["a"] > 1 & df["b"] < 5is parsed in an unexpected way and fails. Write(df["a"] > 1) & (df["b"] < 5). - Wrong condition order in
np.select. The first match wins, so broad conditions placed early hide narrower ones. - Omitting
default. You get0, which mixes badly with text. - Assuming NaN is handled. A comparison with
NaNisFalse, so missing data lands in the fallback branch. - Mismatched list lengths. Every condition needs a matching value.
Using np.select inside assign
Conditional columns fit in a method chain. Use a lambda so the condition reads the frame as built so far.
result = df.assign(
tier=lambda d: np.select(
[d["price"] < 5, d["price"] < 20],
["low", "mid"],
default="high",
)
)
print(result[["item", "tier"]])Summary of the decision
Use np.where when there are exactly two outcomes. Use np.select for three or more, order the conditions from most specific to least, and always set default. Handle NaN as its own first condition when missing data is possible.
Exercise
A DataFrame has a numeric column "score" that may contain NaN. Write code that adds a column "grade" with "A" for scores of 90 or more, "B" for 80 to 89, "C" for 70 to 79, "F" for lower scores, and "missing" for NaN. In what position must the NaN check go, and why?
Show answer
Use np.select with the NaN check first, then the grades from highest to lowest: df["grade"] = np.select( [df["score"].isna(), df["score"] >= 90, df["score"] >= 80, df["score"] >= 70], ["missing", "A", "B", "C"], default="F", ) The NaN check goes first because np.select returns the value of the first true condition. A comparison such as df["score"] >= 70 is False for NaN, so NaN would otherwise fall through to the default "F". The grade conditions run from highest to lowest so that a score of 95 gets "A" and not "C".
Exercise
What does np.select return for a row where no condition is true and you did not pass default? What should you do about it?
Show answer
It returns 0, the default for the default argument. In a text column this gives a wrong or mixed-type value. Pass an explicit default whose type matches the choices, such as default="other" for strings, np.nan for numbers you want to leave missing, or None for text you want to leave missing.