Sub topic 2
Conditional Columns with `numpy.where` and `numpy.select`
Assume you know basic Python, pandas DataFrames and Series, and NumPy arrays. A conditional column assigns a value from a condition without looping through rows. numpy.where handles two outcomes. numpy.select handles several ordered conditions.
Conditional columns with `numpy.where` and `numpy.select`
import numpy as np
import pandas as pd
sales = pd.DataFrame({
"store": ["a", "a", "b", "b"],
"amount": [25, 55, 80, 10],
"name": [" Ann ", "bob", "Cara ", "dan"],
"when": ["2026-01-05", "2026-02-10", "2026-02-12", "2026-03-01"],
})
sales["size"] = np.where(sales["amount"] >= 50, "large", "small")
conditions = [
sales["amount"] < 25,
sales["amount"] < 75,
]
sales["band"] = np.select(
conditions,
["low", "middle"],
default="high",
)np.select checks conditions in order. The first true condition wins. Always provide a suitable default for rows that match none of them.
Index alignment
Pandas vectorised operations match Series by their index labels, not only by their physical positions. This protects calculations when rows have been filtered or reordered, but it can also produce missing values when labels do not overlap.
left = pd.Series([10, 20], index=["a", "b"])
right = pd.Series([1, 2], index=["b", "c"])
print(left + right)
# a NaN
# b 21.0
# c NaNA DataFrame column operation normally stays aligned with its original rows. Check indexes before combining separately created Series.
Vectorised strings and dates with `.str` and `.dt`
Accessors are objects that provide column-wide operations for a data type. The .str accessor handles strings, while .dt handles datetime values.
sales["clean_name"] = sales["name"].str.strip().str.title()
sales["month"] = pd.to_datetime(sales["when"]).dt.month
sales["is_weekend"] = pd.to_datetime(sales["when"]).dt.dayofweek >= 5Group-wise calculations with `groupby` and `transform`
groupby divides rows into groups. transform calculates within each group and returns a result with the original row index, so it can be assigned safely.
sales["store_total"] = sales.groupby("store")["amount"].transform("sum")
sales["share"] = sales["amount"] / sales["store_total"]| Method | Result shape | Typical use |
|---|---|---|
| `groupby().sum()` | One row per group | Group summaries |
| `groupby().transform("sum")` | One value per original row | Row-to-group comparisons |
Exercise
Which function should you use for a two-way conditional column, and which should you use for three ordered outcomes?
Show answer
Use numpy.where for two outcomes and numpy.select for several ordered conditions.