---
title: "dataframe-transform (tc)"
description: pandas 的 transform() 把每組結果貼回每一列，加 headcount、平均 salary、總 bonus 三欄。
url: "https://aaronchan.com/zh/kb/dataframe-transform/"
updated: "2026-09-15"
category: "Code-Python (tc)"
tags:
  - python
---

# dataframe-transform (tc)

`transform()` 跟 `groupby()` 一起用，可以把每一組算出來的結果對應回原本每一列，出來的 DataFrame 長度不變。以下用一個 4 人部門的例子：先補回缺失的 bonus，再用 `transform()` 加三個新欄位（每部門人數、平均 salary、總 bonus）。

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

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