Pandas df.groupby() function
groupby() is one of the most powerful grouping functions in Pandas; it lets you split data into different groups based on the values of one or more columns, and then perform various operations on each group.
Simply put,groupby() implements the "Split-Apply-Combine" workflow: first split the data by conditions, apply the appropriate function to each group, and finally combine the results.
This is very common in data analysis, such as computing average employee salary by department, sales by month, or user counts by region.
Basic syntax and parameters
groupby() is a member function of DataFrame, called via the dot operator . to call it. After calling, it returns a GroupBy object; this object does not display results directly and needs to be used together with aggregation functions.
Syntax format
DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, dropna=True)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| by | str, list, or dict | The column name or list of column names to group by. If a dictionary or function is given, grouping is done by its result. | None |
| axis | int | The axis for grouping; 0 means by row (default), 1 means by column. | 0 |
| level | int or str | If it is a MultiIndex, group by the specified level. | None |
| as_index | bool | If True, the grouping columns become the index of the result; if False, they are kept as regular columns. | True |
| sort | bool | Whether to sort the group labels. Setting it to False can improve performance. | True |
| group_keys | bool | called apply() , whether to add the group keys as an index in the result. |
True |
| observed | bool | If True, only the observed values of categorical variables are shown, rather than all possible values. | False |
| dropna | bool | If True, groups containing NA/null values are dropped. | True |
Return Value
- Return Type:
DataFrameGroupByorSeriesGroupByobject - Description: What is returned is a grouped object, not the final result. You need to call an aggregation function later (such as
sum()、mean()、count(), etc.) to obtain the actual computed results.
Example
Let us thoroughly master groupby() through a series of examples from simple to complex.
Example 1: Grouping by a single column
The most basic usage is grouping by the values of a single column. Suppose we have a sales data table and need to compute total sales by region.
Example
import
pandas
as
pd
Create a simple sales data DataFrame
Simulate a table containing region, product, and sales amount
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
]
}
Create DataFrame
df
=
pd.
DataFrame
(
data
)
(
"Original data:"
)
(
df
)
(
)
Group by the "Region" column and compute the total sales for each region
as_index=True means the region is returned as the index
grouped
=
df.
groupby
(
'Region'
,
as_index
=
True
)
[
'Sales'
]
.
sum
(
)
(
"Total sales after grouping by region:"
)
(
grouped
)
(
)
When as_index=False, the grouping column is kept as a regular column
grouped_df
=
df.
groupby
(
'Region'
,
as_index
=
False
)
[
'Sales'
]
.
sum
(
)
(
"Result when as_index=False:"
)
(
grouped_df
)
Expected output:
原始数据:
地区 产品 销售额
0 华东 B 2000
1 华南 C 1500
2 华北 A 1000
3 华东 B 1800
4 华南 C 2200
5 华北 A 1600
6 华东 A 1200
7 华南 B 2100
Total sales grouped by region:
地区
华东 7100
华南 7300
华北 3600
dtype: int64
The result when as_index=False:
地区 销售额
0 华东 7100
1 华南 7300
2 华北 3600
Code analysis:
df.groupby('地区')The data is divided into three groups by the values of the "Region" column: East China, South China, and North China.['销售额'].sum()indicates summing only the "Sales" column.as_index=True(the default), the returned Series uses the region as the index;as_index=False, the returned DataFrame keeps the region as a regular column, which is more suitable for subsequent processing.
Example 2: Grouping by multiple columns
Sometimes you need to group by multiple columns at once, such as computing sales by region and product.
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'
]
,
'Product'
:
[
'A'
,
'B'
,
'C'
,
'B'
,
'A'
,
'C'
,
'A'
,
'B'
]
,
'Sales'
:
[
1000
,
2000
,
1500
,
1800
,
2200
,
1600
,
1200
,
2100
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original data:"
)
(
df
)
(
)
Group by the "Region" and "Product" columns and compute total sales
Use a list to specify multiple grouping columns
grouped
=
df.
groupby
(
[
'Region'
,
'Product'
]
,
as_index
=
False
)
[
'Sales'
]
.
sum
(
)
(
"Total sales after grouping by region and product:"
)
(
grouped
)
(
)
Use pivot_table to display the results more intuitively
pivot
=
df.
pivot_table
(
values
=
'Sales'
,
index
=
'Region'
,
columns
=
'Product'
,
aggfunc
=
'sum'
,
fill_value
=
0
)
(
"Displayed using pivot_table:"
)
(
pivot
)
Expected output:
原始数据:
地区 产品 销售额
0 华北 A 1000
1 华东 B 2000
2 华南 C 1500
3 华北 B 1800
4 华东 A 2200
5 华南 C 1600
6 华北 A 1200
7 华东 B 2100
Total sales grouped by region and product:
地区 产品 销售额
0 华东 A 2200
1 华东 B 4100
2 华南 C 3100
3 华北 A 2200
4 华北 B 1800
Use pivot_table to display:
产品 A B C
地区
华北 2200 1800 0
华东 2200 4100 0
华南 0 0 3100
Code analysis:
['地区', '产品']Using a list lets you group by multiple columns at once, producing a multi-level index in the result.as_index=False, the grouping columns are kept as regular columns in the result, making them easy to view and process later.pivot_table()provides a similar cross-tabulation feature that can present grouping results in a more intuitive way.
Example 3: Grouping using dictionaries and functions
groupby() Not only can you group by column names, but you can also define grouping rules through dictionaries or functions, which is very useful when custom grouping logic is needed.
Example
import
pandas
as
pd
Create student score data
data
=
{
'Name'
:
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
,
'Zhao Liu'
,
'Sun Qi'
,
'Zhou Ba'
]
,
'Chinese'
:
[
85
,
92
,
78
,
88
,
95
,
82
]
,
'Math'
:
[
90
,
85
,
92
,
78
,
88
,
91
]
,
'English'
:
[
88
,
90
,
85
,
92
,
87
,
89
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original student score data:"
)
(
df
)
(
)
1. Custom grouping using a dictionary
Suppose we want to group by "surname" (Zhang, Li, and Wang in one group; Zhao, Sun, and Zhou in another)
def
get_surname_group
(
name
)
:
"""Return the group name based on the surname"""
if
name
in
[
'Zhang San'
,
'Li Si'
,
'Wang Wu'
]
:
return
'Group 1'
else
:
return
'Group 2'
Use the apply function to group
grouped
=
df.
groupby
(
get_surname_group
)
.
mean
(
numeric_only
=
True
)
(
"Custom grouping using a function (computing the average score of each group):"
)
(
grouped
)
(
)
2. Using a dictionary to map the grouping of a specific column
Divide Chinese scores into two groups, "Excellent" and "Good", by numeric range
score_mapping
=
{
'Chinese'
:
lambda
x:
'Excellent'
if
x >
;=
90
else
'Good'
}
Group the Chinese column by conditions
grouped_by_score
=
df.
groupby
(
lambda
x:
'Excellent'
if
df.
loc
[
x
,
'Chinese'
]
>
;=
90
else
'Good'
)
.
mean
(
numeric_only
=
True
)
(
"Grouped by Chinese score (>=90 is Excellent):"
)
(
grouped_by_score
)
Expected output:
原始学生成绩数据:
姓名 语文 数学 英语
0 张三 85 90 88
1 李四 92 85 90
2 王五 78 92 85
3 赵六 88 78 92
4 孙七 95 88 87
5 周八 82 91 89
使用函数自定义分组(计算每组平均分):
语文 数学 英语
姓名
第一组 85.000000 89.000000 87.666667
第二组 88.333333 85.666667 89.333333
按语文成绩分组(>=90为优秀):
语文 数学 英语
语文
优秀 93.500000 86.500000 88.500000
良好 83.250000 89.500000 88.750000
Code analysis:
- Custom function grouping can handle complex grouping logic, as long as the function returns a value to group by.
- Use
numeric_only=TrueThe parameter lets you aggregate only numeric columns, avoiding errors when operating on non-numeric columns (such as names). - Dictionary mapping can fulfill the need to "divide different columns into different groups by conditions".
Example 4: Iterating over groups
Sometimes we need to perform more complex custom operations on each group; in that case, we can iterate over the grouped object.
Example
import
pandas
as
pd
Create sales data
data
=
{
'Region'
:
[
'North China'
,
'East China'
,
'South China'
,
'North China'
,
'East China'
,
'South China'
]
,
'Product'
:
[
'A'
,
'B'
,
'C'
,
'B'
,
'A'
,
'C'
]
,
'Sales'
:
[
1000
,
2000
,
1500
,
1800
,
2200
,
1600
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original data:"
)
(
df
)
(
)
Iterate over each group for processing
(
"Detailed information for each group:"
)
(
"-"
40
)
for
group_name
,
group_data
in
df.
groupby
(
'Region'
)
:
(
f
"nGroup name: {group_name}"
)
(
f
"Number of rows in this group: {len(group_data)}"
)
(
f
"Total sales of this group: {group_data['Sales'].sum()}"
)
(
f
"Average sales of this group: {group_data['Sales'].mean():.2f}"
)
(
"-"
40
)
Expected output:
原始数据:
地区 产品 销售额
0 华东 B 2000
1 华南 C 1500
2 华北 A 1000
3 华东 B 1800
4 华南 C 2200
5 华北 B 1800
Details for each group:
----------------------------------------
分组名称: 华东
该组数据行数: 2
该组销售总额: 3800
该组平均销售额: 1900.00
----------------------------------------
分组名称: 华南
该组数据行数: 2
3700
1850.00
----------------------------------------
分组名称: 华北
该组数据行数: 2
2800
1400.00
----------------------------------------
Code analysis:
groupby()The returned grouped object can be iterated directly, with each iteration returning a tuple: (group name, that group's data).- In this way, you can perform arbitrarily complex custom operations on each group.
- In practice, this approach is often used to generate complex reports or perform data cleaning.
Tip:
groupby()The returned GroupBy object is "lazy" and does not compute results immediately. Only when an aggregation function is called (such assum()、mean()、count(), etc.) or when iteration occurs is the computation actually performed.
Common Pandas functions