Show contents
Chapter 4 of 7 · 20 min
Group, summarise, join
By the end of this chapter, you'll be able to
- Group rows with groupby and compute a summary per group
- Compute several statistics at once with agg
- Count occurrences with value_counts and cross two criteria with pivot_table
- Join two tables with merge
Split, apply, combine
groupby always follows the same pattern: it splits the table into groups by a column, applies a calculation to each group, then combines the results into a new table.
import io
import pandas as pd
csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\ngroundnut,Thiès,60,640\nmillet,Ziguinchor,90,310\n"
sales = pd.read_csv(io.StringIO(csv))
sales["amount"] = sales["kg"] * sales["price_kg"]
by_region = sales.groupby("region")["amount"].sum()
print(by_region)
print(by_region.sort_values(ascending=False).index[0])
region
Kaolack 88000
Thiès 120900
Ziguinchor 65400
Name: amount, dtype: int64
Thiès
The result is a Series whose index is made of the regions, in alphabetical order. You can then sort it like any Series.
The results are gathered in a Series indexed by region.
Text description of the animation
- We start from all the sales, mixed together.
- groupby("region") puts each row in its region's group.
- The requested calculation applies to each group separately.
- The results are gathered in a Series indexed by region.
Several statistics at once
agg computes several summaries in one go. You can name each column of the result:
import io
import pandas as pd
csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\ngroundnut,Thiès,60,640\nmillet,Ziguinchor,90,310\n"
sales = pd.read_csv(io.StringIO(csv))
sales["amount"] = sales["kg"] * sales["price_kg"]
summary = sales.groupby("product").agg(
sales=("amount", "count"),
total_kg=("kg", "sum"),
avg_price=("price_kg", "mean"),
turnover=("amount", "sum"),
)
print(summary.sort_values("turnover", ascending=False))
sales total_kg avg_price turnover
product
millet 3 410 303.333333 123900
groundnut 2 140 645.000000 90400
mango 1 150 250.000000 37500
cowpea 1 45 500.000000 22500
Each argument is written name=(column, function). Common functions: count, sum, mean, median, min, max.
Count and cross
value_counts counts the occurrences of each value, from most to least frequent. pivot_table crosses two criteria, like a spreadsheet pivot table:
import io
import pandas as pd
csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\ngroundnut,Thiès,60,640\nmillet,Ziguinchor,90,310\n"
sales = pd.read_csv(io.StringIO(csv))
print(sales["product"].value_counts())
print(sales.pivot_table(index="product", columns="region", values="kg", aggfunc="sum", fill_value=0))
product
millet 3
groundnut 2
cowpea 1
mango 1
Name: count, dtype: int64
region Kaolack Thiès Ziguinchor
product
cowpea 0 45 0
groundnut 80 60 0
mango 0 0 150
millet 120 200 90
fill_value=0 puts 0 in the cells without sales (otherwise, pandas would put NaN there).
Join two tables
Information is often spread across several tables. merge links them by a common column, like a join in SQL:
import io
import pandas as pd
sales = pd.read_csv(io.StringIO("product,region,kg\nmillet,Kaolack,120\ngroundnut,Thiès,80\nmango,Ziguinchor,150\nfonio,Kaolack,30\n"))
products = pd.read_csv(io.StringIO("product,family\nmillet,cereal\nfonio,cereal\ngroundnut,oilseed\n"))
full = sales.merge(products, on="product", how="left")
print(full)
print(full.groupby("family")["kg"].sum())
product region kg family
0 millet Kaolack 120 cereal
1 groundnut Thiès 80 oilseed
2 mango Ziguinchor 150 NaN
3 fonio Kaolack 30 cereal
family
cereal 150
oilseed 80
Name: kg, dtype: int64
how="left" keeps all the sales, even those whose product is missing from the second table (mango gets NaN). groupby then ignores the rows whose family is missing.
Mini-lab: the cooperative's dashboardPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: each region's share
Compute, for each region, the turnover and its share of the total as a percentage, rounded to 1 decimal place. Display the result from the biggest share to the smallest.
csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\ngroundnut,Thiès,60,640\nmillet,Ziguinchor,90,310\n"
Hint 1
amount column, then groupby("region")["amount"].sum().Hint 2
by_region / by_region.sum() * 100. round(1) rounds.Show the solution and common mistakes
import io
import pandas as pd
csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\ngroundnut,Thiès,60,640\nmillet,Ziguinchor,90,310\n"
sales = pd.read_csv(io.StringIO(csv))
sales["amount"] = sales["kg"] * sales["price_kg"]
shares = sales.groupby("region")["amount"].sum().to_frame("turnover")
shares["share_pct"] = (shares["turnover"] / shares["turnover"].sum() * 100).round(1)
print(shares.sort_values("share_pct", ascending=False))
turnover share_pct
region
Thiès 120900 44.1
Kaolack 88000 32.1
Ziguinchor 65400 23.8
to_frame("turnover") turns the Series into a one-column DataFrame, so that you can add another column. Quick check: the shares add up to 100%.
Common mistakes:
- Computing the share from
kginstead ofamount: you would get the share of volumes, not of turnover. The two do not tell the same story, because the prices per kilo differ. - Rounding before dividing: small rounding errors add up. Always round at the end, for display.
Summary
- 1groupby splits the table into groups, applies a calculation to each and combines the results.
- 2agg computes several statistics at once, with chosen column names.
- 3value_counts counts occurrences; pivot_table crosses two criteria.
- 4merge links two tables by a common column; how="left" keeps every row of the first.
- 5A mean of means is not the overall mean: recompute from the original rows.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.