Pandas groupby.agg() Function
groupby.agg() is one of the most powerful aggregation functions in Pandas; it allows you to apply multiple different aggregation functions to grouped data at the same time.
The difference between sum()、mean() unlike single aggregation functions such asagg() it can compute multiple statistical metrics at once, such as the sum, mean, maximum, and minimum of each group.
In data analysis, it is often necessary to perform multiple types of statistical analysis on data at the same time;agg() the function can make this process concise and efficient.
Basic syntax and parameters
agg() is a member function of the GroupBy object; you must first use groupby() to group the data before calling it.
Syntax format
GroupBy.agg(func=None, axis=0, *args, engine=None, engine_kwargs=None, **kwargs)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| func | str, list, dict, or callable | Aggregation function. Can be a single function name, a list of functions, or a dictionary mapping columns to different functions. | None |
| axis | int | The axis along which to apply the aggregation; 0 means by row (grouping dimension), 1 means by column. | 0 |
| args | tuple | Extra positional arguments passed to the aggregation 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 the result of grouped aggregation; the structure depends on the func parameter and the grouping method.
Example
Let us thoroughly master groupby.agg() through a series of examples from simple to complex.
Example 1: Using Built-in Aggregation Functions
The simplest way is to directly use built-in Pandas aggregation function names such as 'sum', 'mean', 'max', 'min', 'count', etc.
Example
import
pandas
as
pd
Create a sales data DataFrame
data
=
{
'Region'
:
[
'North China'
,
'East China'
,
'South China'
,
'North China'
,
'East China'
,
'South China'
,
'North China'
,
'East China'
]
,
'Product'
:
[
'A'
,
'B'
,
'C'
,
'B'
,
'A'
,
'C'
,
'A'
,
'B'
]
,
'Sales'
:
[
1000
,
2000
,
1500
,
1800
,
2200
,
1600
,
1200
,
2100
]
,
'quantity'
:
[
10
,
20
,
15
,
18
,
22
,
16
,
12
,
21
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original sales data:"
)
(
df
)
(
)
Group by "Region" and apply multiple aggregation functions to the "Sales" column
Specify multiple aggregation functions using a list of strings
result
=
df.
groupby
(
'Region'
)
[
'Sales'
]
.
agg
(
[
'sum'
,
'mean'
,
'max'
,
'min'
,
'count'
]
)
(
"Summary statistics of sales for each region:"
)
(
result
)
(
)
Aggregate both the "Sales" and "Quantity" columns
result_all
=
df.
groupby
(
'Region'
)
.
agg
(
{
'Sales'
:
[
'sum'
,
'mean'
]
,
'quantity'
:
[
'sum'
,
'mean'
]
}
)
(
"Comprehensive statistics of sales and quantity for each region:"
)
(
result_all
)
Running result:
Original sales data:
地区 产品 销售额 数量
0 华北 A 1000 10
1 华东 B 2000 20
2 华南 C 1500 15
3 华北 B 1800 18
4 华东 A 2200 22
5 华南 C 1600 16
6 华北 A 1200 12
7 华东 B 2100 21
# Summary statistics of sales by region:
sum mean max min count
地区
华东 7100 1775.0 2200 2000 4
华南 3100 1550.0 1600 1500 2
华北 4000 1333.333333 1800 1000 3
Comprehensive statistics of sales and quantity in each region:
销售额 数量
sum mean sum mean
地区
华东 7100 1775.0 83 20.75
华南 3100 1550.0 31 15.50
华北 4000 1333.333333 40 13.33
Code analysis:
['sum', 'mean', 'max', 'min', 'count']Using a list allows you to specify multiple aggregation functions at once.- The returned result is a DataFrame whose column names are composed of the function names and the original column names (a MultiIndex).
- Using a dictionary allows you to specify different aggregation functions for different columns.
Example 2: Using Custom Aggregation Functions
In addition to built-in functions,agg() custom functions are also supported, greatly extending its flexibility.
Example
import
pandas
as
pd
import
numpy
as
np
Create student score data
data
=
{
'class'
:
[
'A'
,
'A'
,
'A'
,
'B'
,
'B'
,
'B'
,
'B'
,
'A'
]
,
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
,
'Zhao Liu'
,
'Sun Qi'
,
'Zhou Ba'
,
'Wu Jiu'
,
'Zheng Shi'
]
,
'Chinese'
:
[
85
,
92
,
78
,
88
,
95
,
82
,
90
,
87
]
,
'Math'
:
[
90
,
85
,
92
,
78
,
88
,
91
,
85
,
89
]
}
df
=
pd.
DataFrame
(
data
)
(
"Student score data:"
)
(
df
)
(
)
Define a custom aggregation function
def
range_func
(
x
)
:
"""Compute the difference between the maximum and minimum (range)"""
return
x.
max
(
)
- x.
min
(
)
def
coefficient_of_variation
(
x
)
:
"""Compute the coefficient of variation (standard deviation / mean)"""
return
x.
std
(
)
/ x.
mean
(
)
100
Aggregate using custom functions
You can pass a function name (string) or a function object directly
result
=
df.
groupby
(
'class'
)
.
agg
(
{
'Chinese'
:
[
'sum'
,
'mean'
,
range_func
]
,
For Chinese: sum, mean, range
'Math'
:
[
'sum'
,
'mean'
,
coefficient_of_variation
]
For Math: sum, mean, coefficient of variation
}
)
(
"Custom statistics for each class:"
)
(
result
)
(
)
You can also use custom functions directly in a list
result2
=
df.
groupby
(
'class'
)
[
'Math'
]
.
agg
(
[
'mean'
,
range_func
,
'std'
]
)
(
"Statistics of math scores for each class (including custom range and standard deviation):"
)
(
result2
)
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
Custom statistics for each class:
语文 数学
sum mean range_func sum mean coefficient_of_variation
班级
A 342 85.5 14.0 425 88.25 5.019099
B 355 88.75 12.0 342 85.5 7.030
各班级数学成绩的统计(包含自定义极差和统计):
班级
A 88.25 5.0 2.692582
B 85.50 13.0 6.0
Code analysis:
- A custom function receives a Series as an argument and returns a scalar value.
- A function name can be passed as a string (such as
'sum'), or you can pass a function object directly. - Using custom functions enables arbitrarily complex aggregation logic.
Example 3: Using String Aliases and lambda Functions
agg() Multiple ways of specifying functions are supported, including lambda expressions and built-in string aliases.
Example
import
pandas
as
pd
Create employee salary data
data
=
{
'Department'
:
[
'sales'
,
'sales'
,
'Ji shu' (a Chinese phrase)
,
'Ji shu' (a Chinese phrase)
,
'Administration'
,
'Administration'
,
'sales'
,
'Ji shu' (a Chinese phrase)
]
,
'Position'
:
[
'Specialist'
,
'Manager'
,
'Specialist'
,
'Manager'
,
'Specialist'
,
'Manager'
,
'Specialist'
,
'Manager'
]
,
'Salary'
:
[
5000
,
8000
,
7000
,
12000
,
4500
,
9000
,
5500
,
11000
]
,
'Years of Service'
:
[
2
,
5
,
3
,
8
,
1
,
6
,
2
,
7
]
}
df
=
pd.
DataFrame
(
data
)
(
"Employee salary data:"
)
(
df
)
(
)
Use lambda functions for flexible custom calculations
Compute the difference between the median and mean salary in each department
result
=
df.
groupby
(
'Department'
)
.
agg
(
{
'Salary'
:
[
(
'Average Salary'
,
'mean'
)
,
Give aliases to aggregation results
(
'Highest Salary'
,
'max'
)
,
(
'Lowest Salary'
,
'min'
)
,
(
'Salary Range'
,
lambda
x: x.
max
(
)
- x.
min
(
)
)
]
,
'Years of Service'
:
[
(
'Average Years of Service'
,
'mean'
)
,
(
'Max Years of Service'
,
'max'
)
,
(
'Min Years of Service'
,
'min'
)
]
}
)
(
"Comprehensive statistics of salary and years of service for each department:"
)
(
result
)
(
)
Using the shorthand form of agg
result2
=
df.
groupby
(
'Department'
)
[
'Salary'
]
.
agg
(
Average
=
'mean'
,
Sum
=
'sum'
,
Count
=
'count'
)
(
"Aggregation results using named arguments:"
)
(
result2
)
Running result:
Employee salary data:
部门 岗位 工资 工龄
0 销售 专员 5000 2
1 销售 经理 8000 5
2 技术 专员 7000 3
3 技术 经理 12000 8
4 行政 专员 4500 1
5 行政 经理 9000 6
6 销售 专员 5500 2
7 技术 经理 11000 7
Comprehensive statistics of salary and seniority for each department:
工资 工龄
平均工资 最高工资 最低工资 工资极差 平均工龄 最高工龄 最低工龄
部门
技术 10000.0 12000 7000 5000 6.0 8 3
行政 6750.0 9000 4500 4500 3.5 6 1
销售 6166.666667 8000 5000 3000 3.0 5 1
Using aggregation results in named parameter form:
平均 总和 人数
部门
技术 10000.0 30000 3
行政 6750.0 13500 2
销售 6166.666667 18500 3
Code analysis:
- Using tuples
('别名', '函数名')allows you to assign custom names to aggregation result columns. - Lambda expressions can be used directly in
agg()to implement simple custom logic. - The named-argument form (keyword arguments) allows you to specify names for result columns more intuitively.
Example 4: Grouping by Multiple Columns with agg
agg() It can also be used with multi-column grouping to handle more complex data analysis needs.
Example
import
pandas
as
pd
Create sales data
data
=
{
'Region'
:
[
'North China'
,
'East China'
,
'South China'
,
'North China'
,
'East China'
,
'South China'
,
'North China'
,
'East China'
,
'South China'
]
,
'Product'
:
[
'A'
,
'B'
,
'C'
,
'B'
,
'A'
,
'C'
,
'A'
,
'B'
,
'C'
]
,
'Sales'
:
[
1000
,
2000
,
1500
,
1800
,
2200
,
1600
,
1200
,
2100
,
1700
]
,
'Profit'
:
[
200
,
400
,
300
,
360
,
440
,
320
,
240
,
420
,
340
]
}
df
=
pd.
DataFrame
(
data
)
(
"Sales data:"
)
(
df
)
(
)
Group by region and product, applying multiple aggregations to sales and profit
result
=
df.
groupby
(
[
'Region'
,
'Product'
]
)
.
agg
(
{
'Sales'
:
[
'sum'
,
'mean'
,
'count'
]
,
'Profit'
:
[
'sum'
,
'mean'
]
}
)
(
"Aggregation results grouped by region and product:"
)
(
result
)
(
)
Use reset_index to convert to a normal DataFrame format
result_flat
=
df.
groupby
(
[
'Region'
,
'Product'
]
,
as_index
=
False
)
.
agg
(
{
'Sales'
:
[
'sum'
,
'mean'
]
,
'Profit'
:
[
'sum'
,
'mean'
]
}
)
Flatten the MultiIndex columns
result_flat.
columns
=
[
'_'
.
join
(
col
)
.
strip
(
'_'
)
for
col
in
result_flat.
columns
.
values
]
(
"Flattened result:"
)
(
result_flat
)
Running result:
Sales data:
地区 产品 销售额 利润
0 华北 A 1000 200
1 华东 B 2000 400
2 华南 C 1500 300
3 华北 B 1800 360
4 华东 A 2200 440
5 华南 C 1600 320
6 华北 A 1200 240
7 华东 B 2100 420
9 华南 C 1700 340
Aggregated results grouped by region and product:
销售额 利润
sum mean count sum mean
地区 产品
华东 A 2200 2200.0 1 440 440.0
B 4100 2050.0 2 4100 4100.0
华南 C 3100 1550.0 2 3100 1550.0
华北 A 2200 1100.0 2 440 220.0
B 1800 1800.0 1 360 360.0
Flattened result:
地区 产品 销售额_sum 销售额_mean 利润_sum 利润_mean
0 华东 A 2200 2200.0 440 440.0
1 华东 B 4100 2050.0 820 410.0
2 华南 C 3100 1550.0 660 330.0
3 华北 A 2200 1100.0 440 220.0
4 华北 B 1800 1800.0 360 360.0
Code analysis:
- Grouping by multiple columns produces a MultiIndex.
- Use
as_index=Falseallows you to keep the grouping columns as normal columns. - Pass
columnsRenaming can flatten a MultiIndex into a single level.
Tip:
agg()is one of the most commonly used functions in grouped aggregation; it can compute multiple statistical metrics at once and supports custom functions, making it highly flexible. It is recommended to master its various usages in real projects.
Common Pandas functions