GroupBy, Aggregation, and Pivot Tables
Summarize data with groupby operations and pivot tables.
GroupBy, Aggregation, and Pivot Tables is a free Python Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
groupby Basics
df.groupby("col") splits the DataFrame into groups by unique values of the column. Chain an aggregation to get results.
import pandas as pd
df = pd.DataFrame({
"dept":["HR","IT","HR","IT","HR"],
"salary":[60,80,65,90,70]
})
print(df.groupby("dept")["salary"].mean())
# HR 65.0
# IT 85.0Multiple Aggregation Functions
Use agg() to apply multiple aggregation functions at once.
import pandas as pd
df = pd.DataFrame({"dept":["HR","IT","HR","IT"],"sal":[60,80,65,90]})
result = df.groupby("dept")["sal"].agg(["mean","max","count"])
print(result)Named Aggregations
Use keyword arguments in agg() to name output columns explicitly (Pandas 0.25+).
import pandas as pd
df = pd.DataFrame({"dept":["HR","IT","HR","IT"],"sal":[60,80,65,90]})
result = df.groupby("dept").agg(
avg_sal=("sal","mean"),
max_sal=("sal","max"),
count=("sal","size")
)
print(result)groupby on Multiple Columns
Pass a list of columns to create hierarchical groups.
import pandas as pd
df = pd.DataFrame({
"year":[2023,2023,2024,2024],
"dept":["HR","IT","HR","IT"],
"sal":[60,80,65,90]
})
print(df.groupby(["year","dept"])["sal"].sum())transform()
transform returns a Series aligned to the original index — useful for adding group-level statistics back to the original DataFrame.
import pandas as pd
df = pd.DataFrame({"dept":["HR","IT","HR","IT"],"sal":[60,80,65,90]})
df["dept_avg"] = df.groupby("dept")["sal"].transform("mean")
print(df)filter()
filter(func) keeps only groups where the function returns True.
import pandas as pd
df = pd.DataFrame({"dept":["HR","IT","HR"],"sal":[60,80,65]})
# Keep only departments with mean salary > 70:
result = df.groupby("dept").filter(lambda g: g["sal"].mean() > 70)
print(result)pivot_table
pd.pivot_table creates a spreadsheet-style summary with custom aggregation.
import pandas as pd
df = pd.DataFrame({
"year":[2023,2023,2024,2024],
"region":["East","West","East","West"],
"sales":[100,150,120,200]
})
pt = pd.pivot_table(df, values="sales",
index="year", columns="region",
aggfunc="sum")
print(pt)crosstab
pd.crosstab computes a cross-tabulation — useful for counting combinations of categorical values.
import pandas as pd
df = pd.DataFrame({"gender":["M","F","M","F","M"],"result":["pass","pass","fail","fail","pass"]})
print(pd.crosstab(df["gender"], df["result"]))apply()
apply(func) applies a custom function to each group's DataFrame (axis=0) or each row/column (axis=1).
import pandas as pd
df = pd.DataFrame({"dept":["HR","IT","HR"],"sal":[60,80,65]})
def range_sal(g):
return g["sal"].max() - g["sal"].min()
print(df.groupby("dept").apply(range_sal))unstack for Reshaping
After a multi-level groupby, use unstack() to move the innermost index level into columns.
import pandas as pd
df = pd.DataFrame({"year":[2023,2023,2024],"dept":["HR","IT","HR"],"sal":[60,80,65]})
result = df.groupby(["year","dept"])["sal"].mean().unstack()
print(result)Resample for Time Series
resample("M") groups a time-series DataFrame by calendar period, enabling monthly/yearly aggregations.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=90, freq="D")
df = pd.DataFrame({"sales": range(90)}, index=idx)
monthly = df.resample("ME").sum()
print(monthly)Quick Check
What does groupby().transform("mean") return?
Recap
groupby splits data into groups for aggregation. Use agg() for multiple functions, transform() to broadcast group stats back, filter() to drop groups, and pivot_table()/crosstab() for cross-dimensional summaries.
Frequently asked questions
Is the “GroupBy, Aggregation, and Pivot Tables” lesson free?
Yes — the full text of “GroupBy, Aggregation, and Pivot Tables” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “GroupBy, Aggregation, and Pivot Tables”?
Summarize data with groupby operations and pivot tables. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “GroupBy, Aggregation, and Pivot Tables” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Series and DataFrame Fundamentals
- Indexing, Filtering, and Boolean Masks
- GroupBy, Aggregation, and Pivot Tables
- Merging, Joining, and Data Cleaning