Data analysis with pandas · Lesson 11 of 15
Pivot tables and crosstab
Reshape a long list of sales into a summary grid with pivot_table, add totals with margins, and count combinations with pd.crosstab.
A pivot table turns a long list into a grid: one row per shop, one column per month, a total in each cell. If you have built one in a spreadsheet, the idea is the same; in pandas it is one function call.
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "North", "South", "South", "North", "South", "East"],
"month": ["Jan", "Feb", "Jan", "Feb", "Jan", "Jan", "Feb"],
"item": ["bread", "bread", "bread", "cake", "cake", "cake", "bread"],
"sales": [120, 140, 90, 60, 45, 30, 80],
})
print(df)shop month item sales 0 North Jan bread 120 1 North Feb bread 140 2 South Jan bread 90 3 South Feb cake 60 4 North Jan cake 45 5 South Jan cake 30 6 East Feb bread 80
Each row is one sale record: which shop, which month, which item, how much in €.
pivot_table
Tell pivot_table what goes down the side (index), across the top (columns), what to put in the cells (values) and how to combine rows that land in the same cell (aggfunc). Always write aggfunc: if you leave it out, pandas takes the mean, not the sum. fill_value=0 writes 0 where there is no data instead of NaN.
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "North", "South", "South", "North", "South", "East"],
"month": ["Jan", "Feb", "Jan", "Feb", "Jan", "Jan", "Feb"],
"item": ["bread", "bread", "bread", "cake", "cake", "cake", "bread"],
"sales": [120, 140, 90, 60, 45, 30, 80],
})
grid = df.pivot_table(index="shop", columns="month", values="sales",
aggfunc="sum", fill_value=0)
print(grid)month Feb Jan shop East 80 0 North 140 165 South 60 120
North had two January rows (bread 120 and cake 45), so its January cell is 165.
The months come out in A to Z order (Feb before Jan), because they are text. Pick the order you want with grid[["Jan", "Feb"]]. margins=True adds a total row and column; margins_name names them.
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "North", "South", "South", "North", "South", "East"],
"month": ["Jan", "Feb", "Jan", "Feb", "Jan", "Jan", "Feb"],
"item": ["bread", "bread", "bread", "cake", "cake", "cake", "bread"],
"sales": [120, 140, 90, 60, 45, 30, 80],
})
grid = df.pivot_table(index="shop", columns="month", values="sales",
aggfunc="sum", fill_value=0,
margins=True, margins_name="Total")
print(grid[["Jan", "Feb", "Total"]])month Jan Feb Total shop East 0 80 80 North 165 140 305 South 120 60 180 Total 285 280 565
Other summaries
aggfunc takes the same names as groupby: "mean", "count", "max" and so on. A pivot table is really a groupby on two columns laid out as a grid, as you saw in groupby: totals and averages by group.
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "North", "South", "South", "North", "South", "East"],
"month": ["Jan", "Feb", "Jan", "Feb", "Jan", "Jan", "Feb"],
"item": ["bread", "bread", "bread", "cake", "cake", "cake", "bread"],
"sales": [120, 140, 90, 60, 45, 30, 80],
})
avg = df.pivot_table(index="item", columns="shop", values="sales",
aggfunc="mean")
print(avg)shop East North South item bread 80.0 130.0 90.0 cake NaN 45.0 45.0
NaN means no sales record for that item in that shop.
Counting with crosstab
pd.crosstab(rows, columns) counts how often each combination appears. It is the quickest way to answer "how many of each kind in each group?". normalize="index" turns counts into shares of each row.
import pandas as pd
df = pd.DataFrame({
"class": ["A", "A", "B", "B", "A", "B", "B", "A"],
"result": ["pass", "fail", "pass", "pass", "pass",
"fail", "fail", "pass"],
})
print(pd.crosstab(df["class"], df["result"]))
share = pd.crosstab(df["class"], df["result"], normalize="index")
print((share * 100).round(1))result fail pass class A 1 3 B 2 2 result fail pass class A 25.0 75.0 B 50.0 50.0
melt: grid.reset_index().melt(id_vars="shop") gives one row per shop and month again.✎ Exercise
Make a pivot table of the bakery sales with item down the side, month across the top, the sum of sales in the cells and 0 for empty cells. Print it with the columns in the order Jan, Feb.
Hint: pivot_table(index="item", columns="month", values="sales", aggfunc="sum", fill_value=0), then pick the columns in order.
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "North", "South", "South", "North", "South", "East"],
"month": ["Jan", "Feb", "Jan", "Feb", "Jan", "Jan", "Feb"],
"item": ["bread", "bread", "bread", "cake", "cake", "cake", "bread"],
"sales": [120, 140, 90, 60, 45, 30, 80],
})
# your code here
Expected output:
month Jan Feb item bread 210 220 cake 75 60
Show a solution
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "North", "South", "South", "North", "South", "East"],
"month": ["Jan", "Feb", "Jan", "Feb", "Jan", "Jan", "Feb"],
"item": ["bread", "bread", "bread", "cake", "cake", "cake", "bread"],
"sales": [120, 140, 90, 60, 45, 30, 80],
})
grid = df.pivot_table(index="item", columns="month", values="sales",
aggfunc="sum", fill_value=0)
print(grid[["Jan", "Feb"]])month Jan Feb item bread 210 220 cake 75 60
Check yourself
1. In pivot_table, what does columns="month" do?
The values of the columns field become the column headings of the grid.
2. What does margins=True add?
Margins are the totals along the edges of the grid.
3. What does pd.crosstab(df["a"], df["b"]) put in each cell?
By default crosstab counts how often each pair of values occurs.