Pivot Tables and crosstab()
A pivot table summarises data in a grid: one variable down the rows, another across the columns, and an aggregated value in each cell. If you've used pivot tables in a spreadsheet, pivot_table() is the same idea in code.
From long data to a grid
Here's a season of results from a small 5-a-side football league, one row per match result for a team:
import pandas as pd
results = pd.DataFrame({
"team": ["Owls", "Owls", "Owls", "Foxes", "Foxes", "Foxes", "Bears", "Bears", "Bears", "Owls"],
"venue": ["home", "away", "home", "home", "away", "away", "home", "away", "home", "away"],
"month": ["Apr", "Apr", "May", "Apr", "Apr", "May", "Apr", "May", "May", "May"],
"goals": [3, 1, 4, 2, 2, 0, 1, 3, 2, 2],
})
grid = results.pivot_table(index="team", columns="venue", values="goals", aggfunc="sum")
print(grid)venue away home
team
Bears 3 3
Foxes 2 2
Owls 3 7
Each cell holds the total goals for one team at one venue. The default aggfunc is "mean", so always state the one you mean.
Options: several functions, totals, fill values
import pandas as pd
results = pd.DataFrame({
"team": ["Owls", "Owls", "Owls", "Foxes", "Foxes", "Foxes", "Bears", "Bears", "Bears", "Owls"],
"venue": ["home", "away", "home", "home", "away", "away", "home", "away", "home", "away"],
"month": ["Apr", "Apr", "May", "Apr", "Apr", "May", "Apr", "May", "May", "May"],
"goals": [3, 1, 4, 2, 2, 0, 1, 3, 2, 2],
})
print(results.pivot_table(index="team", columns="month", values="goals",
aggfunc="sum", margins=True, margins_name="Total"))
print(results.pivot_table(index="month", columns="venue", values="goals",
aggfunc=["count", "mean"]).round(2))month Apr May Total
team
Bears 1 5 6
Foxes 4 0 4
Owls 4 6 10
Total 9 11 20
count mean
venue away home away home
month
Apr 2 3 1.50 2.0
May 3 2 1.67 3.0
| Argument | Effect |
|---|---|
index= |
values that become the rows (one column or a list) |
columns= |
values that become the columns |
values= |
the column to aggregate |
aggfunc= |
"sum", "mean", "count", a list, or a dict per column |
fill_value= |
value for empty cells (e.g. 0) |
margins=True |
add row and column totals |
pivot(): reshape without aggregating
pivot() (no _table) only rearranges values; it does no aggregation. That means each (index, column) pair must appear once, otherwise it raises an error:
import pandas as pd
readings = pd.DataFrame({
"date": ["06-01", "06-01", "06-02", "06-02", "06-03"],
"sensor": ["indoor", "outdoor", "indoor", "outdoor", "indoor"],
"temp": [21.5, 14.2, 21.8, 16.9, 22.0],
})
wide = readings.pivot(index="date", columns="sensor", values="temp")
print(wide)sensor indoor outdoor
date
06-01 21.5 14.2
06-02 21.8 16.9
06-03 22.0 NaN
There's no outdoor reading for 06-03, so that cell is NaN. Use pivot() to reshape tidy data, and pivot_table() when duplicates need to be combined.
crosstab(): counting combinations
pd.crosstab() counts how often each pair of values occurs. It's the quickest way to build a frequency table:
import pandas as pd
survey = pd.DataFrame({
"age_group": ["18-30", "31-50", "18-30", "51+", "31-50", "18-30", "51+", "31-50"],
"commute": ["bike", "car", "bus", "car", "bike", "bike", "bus", "car"],
})
print(pd.crosstab(survey["age_group"], survey["commute"]))
print(pd.crosstab(survey["age_group"], survey["commute"], normalize="index").round(2))commute bike bus car
age_group
18-30 2 1 0
31-50 1 0 2
51+ 0 1 1
commute bike bus car
age_group
18-30 0.67 0.33 0.00
31-50 0.33 0.00 0.67
51+ 0.00 0.50 0.50
normalize="index" turns each row into shares that add up to 1: two thirds of the 18–30 group bike to work.
Tip: A pivot table is just a
groupbyplusunstack:df.groupby(["team", "venue"])["goals"].sum().unstack()gives the same grid as the first example. The next lesson coversstack/unstack.
Test yourself
What aggregation does pivot_table use if you don't pass aggfunc?
- sum
- count
- mean
- first
When does df.pivot(...) raise an error that pivot_table would not?
- When there are missing values
- When an index/column pair appears more than once
- When values are text
- When the table is large
Which function counts how often each combination of two categorical columns occurs?
- pd.crosstab
- pd.melt
- pd.concat
- pd.cut