Pandas groupby-transform() Function
groupby.transform() is a function in Pandas for transforming data after grouping. Unlike aggregation functions,aggregation returns a summary result for each group, while transformation returns a result with the same length as the original data。
Simply put,transform() broadcasting the result of the grouped computation back to each row of the original data. This is very useful for computing each member's relative position within a group, within-group standardization, and the difference from the group mean.
Basic syntax and parameters
transform() is a member function of the GroupBy object; you must first use groupby() to group the data before calling it.
Syntax format
GroupBy.transform(func, axis=0, *args, engine=None, engine_kwargs=None, **kwargs)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| func | str, list, dict, or callable | Transformation function. Can be a built-in function name (such as 'mean', 'sum', 'std'), a list of functions, a dictionary mapping columns to different functions, or a custom function. | None |
| axis | int | The axis along which to apply the transformation; 0 means by row (grouping dimension), 1 means by column. | 0 |
| args | tuple | Extra positional arguments passed to the transformation function. | () |
| engine | str | Specify the computation engine, which can be 'cython' or 'numba'. None means Pandas chooses automatically. | None |
| engine_kwargs | dict | A dictionary of extra arguments passed to the underlying engine. | None |
Return Value
- Return Type:
SeriesorDataFrame - Description: Returns a result with the same number of rows as the original data. Each original row receives the computed result of its group.
Example
Let us thoroughly master groupby.transform() through a series of examples from simple to complex.
Example 1: Basic Usage - Compute the Within-Group Mean
transform() The most basic usage is to compute the mean of each group and then broadcast the result back to every row.
Example
import
pandas
as
pd
Create student score data
data
=
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
,
'Zhao Liu'
,
'Sun Qi'
,
'Zhou Ba'
,
'Wu Jiu'
,
'Zheng Shi'
]
,
'class'
:
[
'A'
,
'A'
,
'A'
,
'B'
,
'B'
,
'B'
,
'B'
,
'A'
]
,
'Chinese'
:
[
85
,
92
,
78
,
88
,
95
,
82
,
90
,
87
]
,
'Math'
:
[
90
,
85
,
92
,
78
,
88
,
91
,
85
,
89
]
}
Create DataFrame
df
=
pd.
DataFrame
(
data
)
(
"Student score data:"
)
(
df
)
(
)
Compute the average math score for each class and broadcast it to every row
df
[
'Class Average Math Score'
]
=
df.
groupby
(
'class'
)
[
'Math'
]
.
transform
(
'mean'
)
Compute the difference between each student's score and the class average
df
[
'Difference from Average'
]
=
df
[
'Math'
]
- df
[
'Class Average Math Score'
]
(
"Data after adding class average and difference:"
)
(
df
)
(
)
Compute class averages for multiple columns at the same time
df
[
[
'Class Average Chinese Score'
,
'Class Average Math Score 2'
]
]
=
df.
groupby
(
'class'
)
[
[
'Chinese'
,
'Math'
]
]
.
transform
(
'mean'
)
(
"Data after adding averages of multiple columns:"
)
(
df
)
Running result:
Student grade data:
姓名 班级 语文 数学
0 张三 A 85 90
1 李四 A 92 85
2 王五 A 78 92
3 赵六 B 88 78
4 孙七 B 95 88
5 周八 B 82 91
6 吴九 B 90 85
7 郑十 A 87 89
Adding data with class average and difference:
姓名 班级 语文 数学 班级数学平均分 与平均分差值
0 张三 A 85 90 89.000000 1.000000
1 李四 A 92 85 89.000000 -4.000000
2 王五 A 78 92 89.000000 3.000000
3 赵六 B 88 78 85.666667 -7.666667
4 孙七 B 95 88 85.666667 2.333333
5 周八 B 82 91 85.666667 5.333333
6 吴九 B 90 85 85.666667 -0.666667
7 郑十 A 87 89 89.000000 0.000000
Data after adding multi-column average:
姓名 班级 语文 数学 班级语文平均分 班级数学平均分2
0 张三 A 85 90 85.500000 89.0
1 李四 A 92 85 85.500000 89.0
2 王五 A 78 92 85.500000 89.0
3 赵六 B 88 78 88.750000 85.5
4 孙七 B 95 88 88.750000 85.5
5 周八 B 82 91 88.750000 85.5
6 吴九 B 90 85 88.750000 85.5
7 郑十 A 87 89 85.500000 89.0
Code analysis:
transform('mean')Compute the average math score for each class.- Since Zhang San, Li Si, Wang Wu, and Zheng Shi are all in Class A, their "Class Average Math Score" is the average of Class A's math scores.
- The returned value has the same length as the number of original data rows, which is the key difference between transform and agg.
Example 2: Within-Group Standardization (Z-Score)
transform() Commonly used to compute within-group standardized values, which is very useful for comparing an individual's relative position within a group.
Example
import
pandas
as
pd
Create employee salary data
data
=
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
,
'Zhao Liu'
,
'Sun Qi'
,
'Zhou Ba'
,
'Wu Jiu'
,
'Zheng Shi'
]
,
'Department'
:
[
'sales'
,
'sales'
,
'sales'
,
'Ji shu' (a Chinese phrase)
,
'Ji shu' (a Chinese phrase)
,
'Ji shu' (a Chinese phrase)
,
'Administration'
,
'Administration'
]
,
'Salary'
:
[
5000
,
8000
,
6000
,
9000
,
12000
,
10000
,
4500
,
7000
]
}
df
=
pd.
DataFrame
(
data
)
(
"Employee salary data:"
)
(
df
)
(
)
Compute the Z-Score (standardized score) of each employee's salary within their department
Z-Score = (original value - group mean) / group standard deviation
df
[
'Department Average Salary'
]
=
df.
groupby
(
'Department'
)
[
'Salary'
]
.
transform
(
'mean'
)
df
[
'Department Salary Standard Deviation'
]
=
df.
groupby
(
'Department'
)
[
'Salary'
]
.
transform
(
'std'
)
df
[
'Z-Score'
]
=
(
df
[
'Salary'
]
- df
[
'Department Average Salary'
]
)
/ df
[
'Department Salary Standard Deviation'
]
(
"Data after adding department statistics and Z-Score:"
)
(
df
)
(
)
Use a custom function to compute the Z-Score in one go
def
z_score
(
x
)
:
"""Compute Z-Score"""
return
(
x - x.
mean
(
)
)
/ x.
std
(
)
df
[
'Z-Score2'
]
=
df.
groupby
(
'Department'
)
[
'Salary'
]
.
transform
(
z_score
)
(
"Z-Score computed using a custom function:"
)
(
df
[
[
'Name'
,
'Department'
,
'Salary'
,
'Z-Score2'
]
]
)
Running result:
Employee salary data:
姓名 部门 工资
0 张三 销售 5000
1 李四 销售 8000
2 王五 销售 6000
3 赵六 技术 9000
4 孙七 技术 12000
5 周八 技术 10000
6 吴九 行政 4500
7 郑十 行政 7000
Add department statistics and Z-Score data:
姓名 部门 工资 部门平均工资 部门工资标准差 Z-Score
0 张三 销售 5000 6333.333333 1525.755 -0.872871
1 李四 销售 8000 6333.333333 1525.755 1.092091
2 王五 销售 6000 6333.333333 1525.755 -0.218218
3 赵六 技术 9000 10333.333333 1525.755 -0.872871
4 孙七 技术 12000 10333.333333 1525.755 1.092091
5 周八 技术 10000 10333.333333 1525.755 -0.218218
6 吴九 行政 4500 5750.000000 1767.767 -0.707107
7 郑十 行政 7000 5750.000000 1767.767 0.707107
使用自定义函数计算的 Z-Score:
姓名 部门 工资 Z-Score2
0 张三 销售 5000 -0.872871
1 李四 销售 8000 1.092091
2 王五 销售 6000 -0.218218
3 赵六 技术 9000 -0.872871
4 孙七 技术 12000 1.092091
5 周八 技术 10000 -0.218218
6 吴九 行政 4500 -0.707107
7 郑十 行政 7000 0.707107
Code analysis:
- A Z-Score indicates how many standard deviations the original value is from the mean; a positive value means above the mean, and a negative value means below the mean.
- With the Z-Score, you can eliminate the effect of differences in salary levels across departments and compare an employee's relative position within their department.
- Zhang San's Z-Score is -0.87, indicating his salary is about 0.87 standard deviations below the sales department average.
Example 3: Within-Group Ranking and Percentiles
transform() It can also be used to compute within-group rankings, which is very useful for sorting and competitive analysis.
Example
import
pandas
as
pd
import
numpy
as
np
Create student score data
data
=
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
,
'Zhao Liu'
,
'Sun Qi'
,
'Zhou Ba'
,
'Wu Jiu'
,
'Zheng Shi'
]
,
'class'
:
[
'A'
,
'A'
,
'A'
,
'B'
,
'B'
,
'B'
,
'B'
,
'A'
]
,
'Math'
:
[
90
,
85
,
92
,
78
,
88
,
91
,
85
,
89
]
}
df
=
pd.
DataFrame
(
data
)
(
"Student score data:"
)
(
df
)
(
)
Compute each student's rank within the class (from highest to lowest)
df
[
'Rank Within Class'
]
=
df.
groupby
(
'class'
)
[
'Math'
]
.
transform
(
lambda
x: x.
rank
(
ascending
=
False
)
)
Compute each student's percentile within the class (percentage rank)
df
[
'Percentile Within Class'
]
=
df.
groupby
(
'class'
)
[
'Math'
]
.
transform
(
lambda
x: x.
rank
(
pct
=
True
)
)
(
"Data after adding rank and percentile within class:"
)
(
df
)
(
)
Another use of filling missing values: fill with the within-group mean
data_with_na
=
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
,
'Zhao Liu'
,
'Sun Qi'
,
'Zhou Ba'
]
,
'class'
:
[
'A'
,
'A'
,
'A'
,
'B'
,
'B'
,
'B'
]
,
'Score'
:
[
85
,
np.
nan
,
78
,
88
,
np.
nan
,
82
]
}
df_na
=
pd.
DataFrame
(
data_with_na
)
(
"Data containing missing values:"
)
(
df_na
)
(
)
Fill missing values with the within-group mean
df_na
[
'Filled Score'
]
=
df_na.
groupby
(
'class'
)
[
'Score'
]
.
transform
(
lambda
x: x.
fillna
(
x.
mean
(
)
)
)
(
"Result after filling with the within-group mean:"
)
(
df_na
)
Running result:
Student grade data:
姓名 班级 数学
0 张三 A 90
1 李四 A 85
2 王五 A 92
3 赵六 B 78
4 孙七 B 88
5 周八 B 91
6 吴九 B 85
7 郑十 A 89
Data after adding class rank and percentile:
姓名 班级 数学 班级内排名 班级内百分位
0 张三 A 90 2.0 0.666667
1 李四 A 85 3.0 1.000000
2 王五 A 92 1.0 1.000000
3 赵六 B 78 4.0 0.250000
4 孙七 B 88 2.0 0.500000
5 周八 B 91 1.0 0.750000
6 吴九 B 85 3.0 0.500000
7 郑十 A 89 4.0 0.333333
Data containing missing values:
姓名 班级 成绩
0 张三 A 85.0
1 李四 A NaN
2 王五 A 78.0
3 赵六 B 88.0
4 孙七 B NaN
5 周八 B 82.0
Results after filling with within-group mean:
姓名 班级 成绩 填充后的成绩
0 张三 A 85.0 85.0
1 李四 A NaN 81.5
2 王五 A 78.0 78.0
3 赵六 B 88.0 88.0
4 孙七 B NaN 85.0
5 周八 B 82.0 82.0
Code analysis:
rank(ascending=False)Compute ranks, with higher values placed first.rank(pct=True)Compute the percentile rank, with results between 0 and 1.transform(lambda x: x.fillna(x.mean()))is a common pattern for handling missing values, filling the missing values in each group with that group's mean.
Example 4: Using Custom Transformation Functions
transform() supports custom functions, enabling more complex within-group data transformation logic.
Example
import
pandas
as
pd
import
numpy
as
np
Create stock price data
data
=
{
'Stock Code'
:
[
'AAPL'
,
'AAPL'
,
'AAPL'
,
'AAPL'
,
'GOOG'
,
'GOOG'
,
'GOOG'
,
'GOOG'
]
,
'Date'
:
[
'2024-01-01'
,
'2024-01-02'
,
'2024-01-03'
,
'2024-01-04'
]
2
,
'Closing Price'
:
[
100
,
105
,
102
,
110
,
80
,
85
,
82
,
90
]
}
df
=
pd.
DataFrame
(
data
)
(
"Stock price data:"
)
(
df
)
(
)
Custom function: compute the daily return of each stock
def
calc_daily_return
(
prices
)
:
"""Compute daily return: (today's price - yesterday's price) / yesterday's price"""
return
prices.
pct_change
(
)
Compute the daily return of each stock
df
[
'Daily Return'
]
=
df.
groupby
(
'Stock Code'
)
[
'Closing Price'
]
.
transform
(
calc_daily_return
)
(
"Data after adding daily returns:"
)
(
df
)
(
)
Custom function: compute the normalized value based on the group's maximum and minimum
def
normalize
(
x
)
:
"""Normalization: (x - min) / (max - min)"""
return
(
x - x.
min
(
)
)
/
(
x.
max
(
)
- x.
min
(
)
)
Compute the normalized value of each stock's price
df
[
'Normalized Price'
]
=
df.
groupby
(
'Stock Code'
)
[
'Closing Price'
]
.
transform
(
normalize
)
(
"Data after adding normalized prices:"
)
(
df
)
Running result:
Stock price data:
股票代码 日期 收盘价
0 AAPL 2024-01-01 100
1 AAPL 2024-01-02 105
2 AAPL 2024-01-03 102
3 AAPL 2024-01-04 110
4 GOOG 2024-01-01 80
5 GOOG 2024-01-02 85
6 GOOG 2024-01-03 82
7 GOOG 2024-01-04 90
Data after adding daily return rate:
股票代码 日期 收盘价 日收益率
0 AAPL 2024-01-01 100 NaN
1 AAPL 2024-01-02 105 0.050000
2 AAPL 2024-01-03 102 -0.028571
3 AAPL 2024-01-04 110 0.078431
4 GOOG 2024-01-01 80 NaN
5 GOOG 2024-01-02 85 0.062500
6 GOOG 2024-01-03 82 -0.035294
7 GOOG 2024-01-04 90 0.097561
# Data after adding normalized price:
股票代码 日期 收盘价 日收益率 归一化价格
0 AAPL 2024-01-01 100 NaN 0.000000
1 AAPL 2024-01-02 105 0.050000 0.500000
2 AAPL 2024-01-03 102 -0.028571 0.200000
3 AAPL 2024-01-04 110 0.078431 1.000000
4 GOOG 2024-01-01 80 NaN 0.000000
5 GOOG 2024-01-02 85 0.062500 0.500000
6 GOOG 2024-01-03 82 -0.035294 0.200000
7 GOOG 2024-01-04 90 0.097561 1.000000
Code analysis:
- The transformation function receives a Series (the data within each group).
- The returned Series must have the same length as the input Series.
- The first value is NaN because
pct_change()a relative change is being computed, and the first day has no previous day's data.
Key difference:
agg()andtransform()The difference between them is:agg()returns a summary result for each group (the number of rows equals the number of groups), whiletransform()returns a result with the same length as the original data. A simple way to remember: agg compresses data, while transform preserves the data shape.
Common Pandas functions