Sub topic 16
Reshaping summaries with pivot_table
This chapter assumes you can already use groupby with agg and know that unstack moves an index level into columns. pivot_table is a groupby whose result is laid out as a grid, with one grouping key down the side and another across the top.
From a long summary to a grid
A grouped summary by two keys comes back as a long table with a two-level index. A grid is often easier to read. This code builds the sales data and then the grid:
import pandas as pd
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})
table = df.pivot_table(
index="region",
columns="product",
values="units",
aggfunc="sum",
fill_value=0,
)
print(table)The table holds these totals:
| region | A | B |
|---|---|---|
| East | 8 | 7 |
| North | 10 | 0 |
| South | 12 | 5 |
Each argument has one job:
indexgives the row labels.columnsgives the column labels.valuesnames the column to summarise.aggfuncnames the summary function. It defaults to"mean".fill_valuereplaces cells that have no data.
The same grid comes from df.groupby(["region", "product"])["units"].sum().unstack(fill_value=0). pivot_table packages those steps into one call.
Missing values and empty cells
North with product B has one row, and its units value is missing. The sum skips missing values, so that cell is 0, not missing. Every region and product pair occurs in this data, so fill_value=0 changes nothing here. It matters when a pair has no rows at all. Without fill_value, that cell would show NaN.
Totals and several functions
margins=True adds a row and a column of overall totals. aggfunc also accepts a list, which adds a column level for each function.
with_totals = df.pivot_table(
index="region",
columns="product",
values="units",
aggfunc="sum",
fill_value=0,
margins=True,
margins_name="Total",
)
print(with_totals)
multi = df.pivot_table(
index="region",
values="units",
aggfunc=["sum", "mean"],
)
print(multi)Sorting a pivot table
A pivot table is an ordinary DataFrame, so sorting works as before. Its rows are sorted by index label, so region comes out alphabetical. To rank regions, sort by a column.
print(table.sort_values("A", ascending=False))Choosing between groupby and pivot_table
| Need | Use |
|---|---|
| Long table with named output columns | `groupby` with `agg` |
| Two keys laid out as a grid | `pivot_table` |
| Totals for each row and column | `pivot_table` with `margins=True` |
Exercise
Using the df above, build a table with regions as rows and products as columns that shows the average price, then explain why each cell equals the price of that product.
Show answer
Use df.pivot_table(index="region", columns="product", values="price", aggfunc="mean"). Each product has one fixed price (A is 2.5, B is 4.0) in every region, so the mean of identical values equals that price.