Sub topic 3
Custom Transformations with `apply` in pandas
Assume you know basic Python functions and lambdas, and can create and select pandas DataFrames. Prefer built-in vectorized operations when they express the rule. Use apply when the logic is genuinely custom.
Custom transformations with `apply`
Series.apply calls a function for each value. DataFrame.apply calls a function for each row or column.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
})
df["label"] = df["item"].apply(lambda value: value.upper())
df["price_band"] = pd.cut(
df["price"],
bins=[0, 5, 20, np.inf],
labels=["low", "mid", "high"],
)
df["price_quantile"] = pd.qcut(
df["price"],
q=3,
labels=["low", "mid", "high"],
)
print(df)cut uses fixed numeric boundaries. qcut creates groups with approximately equal numbers of rows. Both can produce missing categories for missing or out-of-range values.
Missing values in derived columns
Missing input usually produces missing output. A custom function must decide what to do with NaN.
df["price_with_fee"] = df["price"].apply(
lambda value: value * 1.1 if pd.notna(value) else np.nan
)Use fillna before or after the calculation when a default is appropriate. Do not silently convert an unknown value into zero unless zero has the correct meaning.
Adding group statistics with `transform`
groupby().transform() calculates a group statistic and returns one result aligned with every original row. This makes it useful for derived columns.
sales = pd.DataFrame({
"region": ["N", "N", "S"],
"amount": [10, 30, 20],
})
sales["region_total"] = sales.groupby("region")["amount"].transform("sum")
sales["region_share"] = sales["amount"] / sales["region_total"]Column position and cleanup
Use insert to place a column at a specific index. Use rename and drop to make the result readable.
sales.insert(1, "amount_x2", sales["amount"] * 2)
sales = sales.rename(columns={"amount": "sales_amount"})
sales = sales.drop(columns=["amount_x2"])Avoiding chained assignment
A chained expression such as df[df["price"] > 10]["price"] = 0 may modify a temporary object instead of df. Use .loc for filtered assignment, or copy the subset deliberately.
df.loc[df["price"] > 10, "price"] = 25
expensive = df.loc[df["price"] > 10].copy()Choosing for speed and clarity
| Need | Preferred tool |
|---|---|
| Arithmetic or comparisons | Vectorized operators |
| Several ordered conditions | `np.select` |
| One custom value-by-value rule | `apply` |
| Group result aligned to rows | `transform` |
Vectorized code is usually faster than Python-level apply. Choose apply when it makes a complex rule clearer and no suitable vectorized operation exists.
Exercise
Which method should you prefer for calculating price multiplied by quantity for every row?
Show answer
Use vectorized multiplication, such as df["price"] * df["quantity"], instead of apply.