Used with groupby(), transform() maps a per-group result back onto every original row, so the DataFrame keeps its length. Here’s a 4-person example: fill the missing bonus, then add three new columns with transform() (headcount, average salary, and total bonus per department).
import pandas as pd # Import pandas
# Example: create or load your DataFrame first
df = pd.DataFrame({
"dept": ["IT", "IT", "HR", "HR"],
"name": ["Alice", "Bob", "Carol", "Dave"],
"salary": [5000, 6000, 5500, 5200],
"bonus": [500, None, 300, None],
})
# 1. Fill missing bonus values with 0 (only affects the 'bonus' column)
df = df.fillna({"bonus": 0})
# 2. Department headcount: number of employees per department
df["headcount"] = df.groupby("dept")["name"].transform("count")
# 3. Department average salary
df["avg_salary"] = df.groupby("dept")["salary"].transform("mean")
# 4. Department total bonus
df["total_bonus"] = df.groupby("dept")["bonus"].transform("sum")
display(df)output:
dept name salary bonus headcount avg_salary total_bonus 0 IT Alice 5000 500.0 2 5500.0 500.0 1 IT Bob 6000 0.0 2 5500.0 500.0 2 HR Carol 5500 300.0 2 5350.0 300.0 3 HR Dave 5200 0.0 2 5350.0 300.0

