Skip to content
Pandas

GroupBy Operations

Split, aggregate, and transform with groupby.

By EZ4Code Team
groupbyaggregation

Code

import pandas as pd

df = pd.DataFrame({
    "dept": ["eng", "eng", "sales", "sales", "hr"],
    "salary": [90, 110, 70, 80, 60],
    "years": [3, 5, 2, 4, 1],
})

# Single aggregation
print(df.groupby("dept")["salary"].mean())

# Multiple aggregations
agg = df.groupby("dept").agg(
    avg_salary=("salary", "mean"),
    max_salary=("salary", "max"),
    headcount=("salary", "size"),
)
print(agg)

# Transform keeps the original shape
df["dept_avg"] = df.groupby("dept")["salary"].transform("mean")

# Filter groups
big = df.groupby("dept").filter(lambda g: g["salary"].sum() > 100)

Explanation

groupby splits the frame into groups, applies a function, and combines the results. Named aggregation gives explicit output column names, while transform broadcasts per-group results back to the original rows. filter keeps entire groups that satisfy a predicate.

More Pandas Snippets