Sub topic 5
Conditional columns with numpy.where and numpy.select
This chapter assumes you can write if/elif/else in Python, build a DataFrame, and use boolean masks like df["qty"] >= 3. It shows how to replace branching inside a row loop with one expression per column.
The loop you are replacing
A common pattern is to loop over rows and pick a label with if/else:
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"] = sizesThe condition is evaluated once per row in Python. A boolean mask evaluates it for every row in one step, and numpy.where uses that mask to choose between two values.
Two outcomes: numpy.where
numpy.where(condition, value_if_true, value_if_false) takes a boolean array and returns a new array. Each position gets the second argument where the condition is True and the third where it is False.
import numpy as np
df["size"] = np.where(df["qty"] >= 3, "bulk", "single")
print(df[["qty", "size"]])The two value arguments can be scalars or whole columns. This example gives bulk orders a 10% discount and leaves other prices unchanged:
df["unit_price"] = np.where(df["qty"] >= 3, df["price"] * 0.9, df["price"])Several outcomes: numpy.select
Nested np.where calls become hard to read after two levels. numpy.select(condlist, choicelist, default) takes a list of conditions and a matching list of results.
conditions = [df["total"] < 40, df["total"] < 60]
df["band"] = np.select(conditions, ["low", "mid"], default="high")
print(df[["total", "band"]])select checks the conditions in order, and the first one that is true for a row decides its result. A total of 30 satisfies both conditions, but it gets "low" because that condition comes first. Order the conditions from most specific to least specific, as you would order elif branches.
Combining conditions
Build compound conditions with & (and), | (or) and ~ (not). Wrap each comparison in parentheses, because these operators bind more tightly than comparisons.
big_and_cheap = (df["qty"] >= 3) & (df["price"] < 12)
df["flag"] = np.where(big_and_cheap, "review", "ok")Python's and, or and not do not work on Series. They raise ValueError: The truth value of a Series is ambiguous.
Common errors
- Forgetting
default. Without it,np.selectfills unmatched rows with0for numeric choices. For string choices, recent NumPy versions raise an error because the default0cannot be combined with text. Always passdefaultexplicitly. - Mixed result types. Choices such as
"low"and0in one result produce an array of strings or objects. Keep every choice the same type. - Lost index.
np.whereandnp.selectreturn plain arrays with no index. Assigning to a column of the same DataFrame is safe. If the DataFrame has been filtered or reordered in between, wrap the result aspd.Series(result, index=df.index). - Both branches always run.
np.wherecomputes both value arguments for all rows before choosing. A branch such asdf["a"] / df["b"]still divides by zero in rows where the condition would have avoided it. This givesinforNaN, which the condition then discards. Check the unused branch for warnings. - Missing values. A comparison with
NaNisFalse, so those rows fall through to the else value or the default. Handle them with an explicit condition such asdf["total"].isna(), placed first.
Exercise
Using the DataFrame above, create a column "tier" from "total" with np.select. Totals of 60 or more are "gold", totals of 30 or more are "silver", and everything else is "basic". Which condition must come first, and what would go wrong if you swapped them?
Show answer
conditions = [df["total"] >= 60, df["total"] >= 30]; df["tier"] = np.select(conditions, ["gold", "silver"], default="basic"). The ">= 60" condition must come first. If ">= 30" came first, every total of 60 or more would also match it and be labelled "silver", because select uses the first true condition.