PY-401 ยท Summarising and joining
groupby: totals per group
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
groupby splits a table into groups that share a value, runs a calculation on each group and puts the results back together. sales.groupby("region")["revenue"].sum() gives one total per region. Use .agg(["sum", "mean", "count"]) for several results at once, and a list of columns to group by two things.
- Total a column per group
- Get several statistics with agg
- Group by two columns
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
import pandas as pdsales = pd.DataFrame({"region": ["North", "South", "North", "East", "South", "North"],"product": ["Tea", "Tea", "Cake", "Tea", "Cake", "Tea"],"revenue": [120, 90, 200, 60, 150, 80],})print(sales.groupby("region")["revenue"].sum())print(sales.groupby("region")["revenue"].agg(["sum", "mean", "count"]).round(1))print(sales.groupby(["region", "product"])["revenue"].sum().reset_index())
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
region
East 60
North 400
South 240
Name: revenue, dtype: int64
sum mean count
region
East 60 60.0 1
North 400 133.3 3
South 240 120.0 2
region product revenue
0 East Tea 60
1 North Cake 200
2 North Tea 200
3 South Cake 150
4 South Tea 90 ๐ฏ Set per_class to the average "score" for each "class" in results, as a Series indexed by class.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
per_class = results.groupby("class")["score"].mean()
- The problemThe sales director asks one question every Monday: "How much did each region make?" Six rows today, sixty thousand next year. The answer is the same single line.
- The Python idea
df.groupby("key")["col"].sum()groupbysplits a table into groups that share a value, runs a calculation on each group and puts the results back together. - In real lifeA ride-hailing company runs
trips.groupby("driver_id")["rating"].mean()every night and contacts drivers whose average drops below 4.5.
Start with a question
The sales director asks one question every Monday: "How much did each region make?" Six rows today, sixty thousand next year. The answer is the same single line.
Most business questions are "per something": revenue per region, orders per customer, average score per class. groupby answers all of them.
Explain it like I'm 10
Tip a bag of sweets on the table and sort them into piles by colour. Then count each pile. groupby is the sorting into piles, sum or count is what you do with each pile.
The technical explanation
Read df.groupby("region")["revenue"].sum() as: split by region, take the revenue column, add up each group.
Any aggregation works after groupby: sum, mean, count, min, max, median, nunique.
.agg(["sum", "mean", "count"]) returns one column per statistic. Named aggregation, .agg(total=("revenue", "sum")), lets you name the result columns.
groupby(["region", "product"]) makes one group per combination. .reset_index() turns the result back into a flat table.
Syntax
df.groupby("key")["col"].sum()
df.groupby("key")["col"].agg(["sum", "mean"])
df.groupby(["a", "b"])["col"].sum().reset_index() Real-world scenario
A ride-hailing company runs trips.groupby("driver_id")["rating"].mean() every night and contacts drivers whose average drops below 4.5.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Pivot tables โQuestions people ask
How do I get a DataFrame instead of a Series from pandas groupby?
Add .reset_index() to the result, or pass as_index=False to groupby. Both give you a flat table with the group values as a normal column.
What is the difference between count and size in pandas groupby?
count gives the number of non-missing values in each column per group. size gives the number of rows per group, including rows with missing values.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner How do I get a DataFrame instead of a Series from pandas groupby?
Add .reset_index() to the result, or pass as_index=False to groupby. Both give you a flat table with the group values as a normal column.
beginner What is the difference between count and size in pandas groupby?
count gives the number of non-missing values in each column per group. size gives the number of rows per group, including rows with missing values.
intermediate What does df.groupby("city")["sales"].sum() return?
One total per city. groupby makes one group per city and sums each.
intermediate Which counts rows in each group?
.count(). count gives the number of non-missing values per group.
Quick revision
Remember
- Total a column per group
- Get several statistics with agg
- Group by two columns
- The groups become the index of the result. Add
.reset_index()to turn them back into a normal column before you save, merge or plot.
Syntax
df.groupby("key")["col"].sum()
df.groupby("key")["col"].agg(["sum", "mean"])
df.groupby(["a", "b"])["col"].sum().reset_index() Official documentation
- Group by: split-apply-combine (docs.python.org)