Pandas Grouping Operations (groupby)
groupby is one of Pandas' most powerful features, allowing you to group data by one or more columns and then perform aggregation, transformation, or filtering operations on each group.
Basic groupby Usage
Grouping by a Single Column
Example
import
pandas
as
pd
Create sample data
df
=
pd.
DataFrame
(
{
"Department"
:
[
"Technology"
,
"Sales"
,
"Technology"
,
"Operations"
,
"Sales"
,
"Technology"
]
,
"Name"
:
[
"Zhang San"
,
"Li Si"
,
"Wang Wu"
,
"Zhao Liu"
,
"Qian Qi"
,
"Sun Ba"
]
,
"Salary"
:
[
12000
,
15000
,
11000
,
18000
,
14000
,
13000
]
}
)
(
"Original data:"
)
(
df
)
(
)
Group by department
grouped
=
df.
groupby
(
"Department"
)
(
f
"Group object: {type(grouped)}"
)
(
f
"Number of groups: {len(grouped)}"
)
(
)
View groups
(
"Data for each group:"
)
for
name
,
group
in
grouped:
(
f
"\nDepartment: {name}"
)
(
group
)
Group and aggregate
Example
import
pandas
as
pd
df
=
pd.
DataFrame
(
{
"Department"
:
[
"Technology"
,
"Sales"
,
"Technology"
,
"Operations"
,
"Sales"
]
,
"Salary"
:
[
12000
,
15000
,
11000
,
18000
,
14000
]
}
)
(
"Average salary by department:"
)
(
df.
groupby
(
"Department"
)
[
"Salary"
]
.
mean
(
)
)
(
)
(
"Sum by department:"
)
(
df.
groupby
(
"Department"
)
[
"Salary"
]
.
sum
(
)
)
(
)
(
"Count by department:"
)
(
df.
groupby
(
"Department"
)
.
size
(
)
)
Grouping by Multiple Columns
Example
import
pandas
as
pd
df
=
pd.
DataFrame
(
{
"Year"
:
[
"2023"
,
"2023"
,
"2024"
,
"2024"
]
,
"Department"
:
[
"Technology"
,
"Sales"
,
"Technology"
,
"Sales"
]
,
"Salary"
:
[
12000
,
15000
,
13000
,
16000
]
}
)
(
"Group by year and department:"
)
(
df.
groupby
(
[
"Year"
,
"Department"
]
)
[
"Salary"
]
.
sum
(
)
)
(
)
Output as a DataFrame
result
=
df.
groupby
(
[
"Year"
,
"Department"
]
)
.
agg
(
{
"Salary"
:
"sum"
}
)
.
reset_index
(
)
(
"Result DataFrame:"
)
(
result
)
Common aggregation functions
Single Aggregation
| function | Description |
|---|---|
sum() |
Sum |
mean() |
Mean |
median() |
Median |
std() |
Standard deviation |
min() / max() |
Minimum/maximum |
count() |
Count |
first() / last() |
First/Last Value |
Example
import
pandas
as
pd
df
=
pd.
DataFrame
(
{
"Department"
:
[
"Technology"
,
"Sales"
,
"Technology"
,
"Operations"
]
,
"Salary"
:
[
12000
,
15000
,
11000
,
18000
]
}
)
Chaining Multiple Aggregations
(
"Chained aggregation:"
)
(
df.
groupby
(
"Department"
)
[
"Salary"
]
.
agg
(
[
"sum"
,
"mean"
,
"max"
,
"min"
]
)
)
Custom Aggregation
Example
import
pandas
as
pd
import
numpy
as
np
df
=
pd.
DataFrame
(
{
"Department"
:
[
"Technology"
,
"Sales"
,
"Technology"
,
"Operations"
]
,
"Salary"
:
[
12000
,
15000
,
11000
,
18000
]
}
)
Custom aggregation function
def
range_func
(
x
)
:
return
x.
max
(
)
- x.
min
(
)
(
"Using a custom function:"
)
(
df.
groupby
(
"Department"
)
[
"Salary"
]
.
agg
(
range_func
)
)
(
)
Named Aggregation (Recommended)
(
"Named aggregation:"
)
(
df.
groupby
(
"Department"
)
.
agg
(
Minimum Salary
=
(
"Salary"
,
"min"
)
,
Maximum Salary
=
(
"Salary"
,
"max"
)
,
Average Salary
=
(
"Salary"
,
"mean"
)
)
)
transform
transform can compute results for each group while preserving the original data shape, returning a result with the same shape as the original data.
Example
import
pandas
as
pd
df
=
pd.
DataFrame
(
{
"Department"
:
[
"Technology"
,
"Sales"
,
"Technology"
,
"Operations"
,
"Sales"
]
,
"Salary"
:
[
12000
,
15000
,
11000
,
18000
,
14000
]
}
)
(
"Original data:"
)
(
df
)
(
)
Compute the average salary of each department and broadcast it to each row
df
[
"Department average salary"
]
=
df.
groupby
(
"Department"
)
[
"Salary"
]
.
transform
(
"mean"
)
(
"Add department average salary:"
)
(
df
)
(
)
Compute each person's salary as a proportion of their department
df
[
"Salary proportion"
]
=
df
[
"Salary"
]
/ df
[
"Department average salary"
]
(
"Salary proportion:"
)
(
df
)
filter Filtering
filter can filter data based on grouping conditions.
Example
import
pandas
as
pd
df
=
pd.
DataFrame
(
{
"Department"
:
[
"Technology"
,
"Sales"
,
"Technology"
,
"Operations"
,
"Sales"
,
"Technology"
]
,
"Salary"
:
[
12000
,
15000
,
11000
,
18000
,
14000
,
13000
]
}
)
(
"Original data:"
)
(
df
)
(
)
Filter departments whose average salary is greater than 13000
(
"Department average salary > 13000:"
)
filtered
=
df.
groupby
(
"Department"
)
.
filter
(
lambda
x: x
[
"Salary"
]
.
mean
(
)
13000
)
(
filtered
)
(
)
Filter groups with more than 2 members
(
"Number of members > 2:"
)
filtered2
=
df.
groupby
(
"Department"
)
.
filter
(
lambda
x:
len
(
x
)
2
)
(
filtered2
)
apply a custom function
apply allows you to apply a custom function to each group.
Example
import
pandas
as
pd
import
numpy
as
np
df
=
pd.
DataFrame
(
{
"Department"
:
[
"Technology"
,
"Sales"
,
"Technology"
,
"Operations"
]
,
"Salary"
:
[
12000
,
15000
,
11000
,
18000
]
}
)
Apply a custom function to each group
result
=
df.
groupby
(
"Department"
)
.
apply
(
lambda
x: pd.
Series
(
{
"Sum"
: x
[
"Salary"
]
.
sum
(
)
,
"Mean"
: x
[
"Salary"
]
.
mean
(
)
}
)
)
(
"Custom aggregation result:"
)
(
result
)
Practical example: Sales data analysis
Example
import
pandas
as
pd
Simulate sales data
sales
=
pd.
DataFrame
(
{
"date"
: pd.
date_range
(
"2024-01-01"
,
periods
=
30
,
freq
=
"D"
)
,
"Product"
:
[
"Phone"
,
"Computer"
,
"Tablet"
]
10
,
"Channel"
:
[
"Online"
]
15
[
"Offline"
]
15
,
"Sales"
:
[
1000
,
2000
,
1500
]
10
}
)
(
"=== Sales Data Analysis ===\n"
)
1. Statistics by product
(
"1. Statistics by product:"
)
product_summary
=
sales.
groupby
(
"Product"
)
[
"Sales"
]
.
agg
(
[
"sum"
,
"mean"
,
"count"
]
)
(
product_summary
)
(
)
2. Statistics by channel
(
"2. Statistics by channel:"
)
channel_summary
=
sales.
groupby
(
"Channel"
)
[
"Sales"
]
.
sum
(
)
(
channel_summary
)
(
)
3. Cross-tabulation by product and channel
(
"3. Product x Channel cross-tabulation:"
)
cross_summary
=
sales.
groupby
(
[
"Product"
,
"Channel"
]
)
[
"Sales"
]
.
sum
(
)
.
unstack
(
)
(
cross_summary
)
(
)
4. Calculate the sales share of each product
(
"4. Sales share:"
)
total
=
sales
[
"Sales"
]
.
sum
(
)
product_pct
=
sales.
groupby
(
"Product"
)
[
"Sales"
]
.
sum
(
)
/ total *
100
(
product_pct.
round
(
2
)
)
groupby is a core operation in data analysis; mastering it lets you efficiently complete a wide range of statistical analysis tasks.