---
title: "dataframe-transform (en)"
description: "pandas transform(): map per-group results back to each row — headcount, avg salary, and total bonus."
url: "https://aaronchan.com/kb/dataframe-transform/"
updated: "2026-09-15"
category: "Code-Python (en)"
tags:
  - python
---

# dataframe-transform (en)

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).

 Copy

```
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
```

![Result of display(df)](https://aaronchan.com/wp-content/uploads/2026/09/transform_output.png)
