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 Series of True and False values, one per row.
Why not an if statement?
A plain Python if works on one value. A column holds many values, so if df["price"] < 5: raises a ValueError because pandas cannot decide whether a whole Series is true. Instead, build a boolean mask and let NumPy pick a value for each row.
Two outcomes with np.where
np.where(condition, value_if_true, value_if_false) checks every row and returns an array. Assign it to a new column.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
df["cheap"] = np.where(df["price"] < 5, "yes", "no")
print(df)The result is yes, no, no. The value arguments can also be columns or expressions, so np.where(df["qty"] > 5, df["price"] * 0.9, df["price"]) applies a discount only on bulk rows.
Several outcomes with np.select
For more than two outcomes, nested np.where calls become hard to read. np.select takes a list of conditions and a list of results.
df["tier"] = np.select(
[df["price"] < 5, df["price"] < 20],
["low", "mid"],
default="high",
)
print(df[["item", "price", "tier"]])For each row, np.select uses the result paired with the first condition that is True. If none match, it uses default.
Common errors
- Wrong order. Conditions are checked in order, and the first match wins. A price of 1.5 satisfies both conditions above, and it gets
lowonly because that condition comes first. Put the most specific condition first. - Forgetting
default. The default is0. In a column of strings this inserts the number 0, which mixes types. Setdefaultexplicitly, for exampledefault="unknown". - Mismatched lengths. The conditions list and the choices list must be the same length, or NumPy raises an error.
- Using
and/or. Combine masks with&,|, and~, and wrap each comparison in parentheses:(df["price"] > 5) & (df["qty"] < 5).
Missing values
A comparison with NaN evaluates to False. So a row with a missing price falls through to the default in np.select, and it gets high in the example above. If missing data should stay visible, add a condition for it first, such as df["price"].isna() paired with "missing".
Exercise
A DataFrame has a numeric column "score". Write an np.select call that labels scores of 90 or more "A", scores of 80 or more "B", and everything else "C". What would go wrong if you listed the "B" condition first?
Show answer
df["grade"] = np.select([df["score"] >= 90, df["score"] >= 80], ["A", "B"], default="C"). If the "B" condition came first, a score of 95 would match it and get "B", because the first true condition wins and "A" would never be assigned.