GroupBy
Split data into groups, aggregate each group and combine the result.
What you will be able to do
- Use groupby("column") to split.
- Use agg with several functions.
- Use named aggregation for clear output.
- Reset the index when you need a flat table.
In plain English
groupby follows split-apply-combine. Choose the grouping column, choose an aggregation and optionally reset the index. Named aggregation makes the output readable.
import pandas as pd
df = pd.DataFrame({
'course': ['HTML', 'CSS', 'CSS', 'SQL'],
'minutes': [12, 18, 22, 9],
})
summary = df.groupby('course').agg(
lessons=('minutes', 'size'),
total=('minutes', 'sum'),
average=('minutes', 'mean'),
).reset_index().sort_values('total', ascending=False)
print(summary)Your turn
EasyAverage minutes per course
Group by course and compute average minutes.
PYTHON · starter
df.groupby('course')Check your understanding before moving on.
Knowledge checkQuestion 1
What are the three stages of a groupby operation?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.