Sub topic 16
Reshaping summaries with pivot_table
This chapter assumes you can build a DataFrame and select columns, and that you know groupby with agg from the previous chapters. Here you will turn a grouped summary into a cross-tabulated table. Rows hold one category, columns hold another, and each cell holds an aggregate.
The examples use the sales DataFrame from earlier in the tutorial.
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],
})What pivot_table does
groupby with two keys returns a long table. Each row is one (region, product) pair. That layout is fine for code but hard to read when you want to compare products within a region. pivot_table groups by two keys, aggregates, and then moves one key into the column headers.
table = df.pivot_table(
index="region",
columns="product",
values="units",
aggfunc="sum",
fill_value=0,
)
print(table)The output looks like this:
product A B
region
East 8.0 7.0
North 10.0 0.0
South 12.0 5.0The four arguments each have one job:
indexnames the column whose values become the row labels.columnsnames the column whose values become the column labels.valuesnames the column to aggregate.aggfuncnames the aggregation. The default is"mean", which surprises people who expect a sum.
The cells are floats because units contains a missing value, so pandas stores the column as float.
The same result with groupby
pivot_table is a convenience over groupby plus unstack. Knowing the equivalent helps when you debug.
same = (
df.groupby(["region", "product"])["units"]
.sum()
.unstack(fill_value=0)
)
print(same)unstack moves the innermost index level, here product, into the columns. Use pivot_table when you want its extras, such as margins and several aggregations at once. Use groupby when the result should stay long.
Missing values and fill_value
North never sold product B with a recorded unit count. The only North/B row has units of NaN. Two different things can produce an empty-looking cell, and they behave differently.
- A group exists but its values are all missing. With
aggfunc="sum"the sum of nothing is0.0, so North/B shows0.0even withoutfill_value. - A group does not exist at all. If North had no product B row, the cell would be
NaNuntilfill_valuereplaced it.
Now try "mean".
mean_table = df.pivot_table(
index="region",
columns="product",
values="units",
aggfunc="mean",
)
print(mean_table)The North/B cell is NaN, because the mean of no valid numbers is undefined. If you add fill_value=0 here, the cell becomes 0. That claims North sold zero units on average, when the truth is that the data is unknown.
The dropna argument is a separate control. By default (dropna=True) it removes columns whose entries are all NaN. It does not change how NaN inside a group is handled. Aggregations skip missing values by default, as in the groupby chapter.
Totals with margins
Set margins=True to add a row and a column of totals. The label defaults to "All" and can be changed with margins_name.
with_totals = df.pivot_table(
index="region",
columns="product",
values="units",
aggfunc="sum",
fill_value=0,
margins=True,
margins_name="Total",
)
print(with_totals)product A B Total
region
East 8.0 7.0 15.0
North 10.0 0.0 10.0
South 12.0 5.0 17.0
Total 30.0 12.0 42.0Margins are computed by applying aggfunc to the original rows, not by adding up the cells. For sum the two agree. For mean, the All cell is the mean of all rows, not the mean of the cell means. The two differ when groups have different sizes.
Several values and several functions
Pass a list to values to summarise more than one column. Pass a dictionary to aggfunc to give each column its own function.
multi = df.pivot_table(
index="region",
columns="product",
values=["units", "price"],
aggfunc={"units": "sum", "price": "mean"},
)
print(multi)The result has two-level column headers: the value name first, then the product. Select a block with multi["units"]. You can also pass a list such as aggfunc=["sum", "count"]. The function name then becomes the outer header.
You can use more than one key on either axis. index=["region", "product"] with no columns gives a long, grouped layout, equivalent to groupby.
Sorting a pivot table
A pivot table is an ordinary DataFrame, so everything from the sorting chapters applies. Rows and columns come out in sorted label order by default. To rank rows by a cell, sort by a column label:
print(table.sort_values("A", ascending=False))To rank rows by a computed total, add a helper column. Then sort by it, and drop it if you do not want it displayed.
ranked = (
table.assign(total=table.sum(axis=1))
.sort_values("total", ascending=False)
)
print(ranked)To reorder the columns, use sort_index(axis=1). For example, table.sort_index(axis=1, ascending=False) puts B before A.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Cells hold averages when you wanted totals | The default `aggfunc` is `"mean"` | Pass `aggfunc="sum"` explicitly |
| Zeros in a table of averages | `fill_value=0` hid missing groups | Remove `fill_value` or fill with a label such as `NaN` |
| Integers turned into floats | A missing value forced a float column | Convert afterwards with `.astype("int64")` once gaps are filled |
| Unexpected multi-level headers | `values` was a list or `aggfunc` was a list | Select the outer level, for example `multi["units"]` |
| Total row sorted into the data | `margins=True` before sorting | Add totals after sorting |
The integer fix works only after no NaN remains. A table filled with fill_value=0 can be cast like this:
print(table.astype("int64"))Choosing between tools
- Use
groupby(...).agg(...)when you want a long table with named columns and plan to sort or filter the result. - Use
pivot_tablewhen a person will read the table and compare across two categories at once. - Use
transformwhen you need group statistics aligned to the original rows rather than a smaller summary.
Exercise
Using the sales DataFrame above, build a region-by-product table of the mean price, then add a total row and column. Why does the "All" cell not equal the sum of the cell values, and which argument sets its label?
Show answer
Use df.pivottable(index="region", columns="product", values="price", aggfunc="mean", margins=True, marginsname="Total"). The label comes from margins_name. The margin cells are means computed over the original rows in that row or column, not sums of the displayed cells, so they are averages and do not add up. Product A rows all have a price of 2.5 and product B rows all have 4.0, so the Total row shows 2.5 and 4.0, and the Total column shows the mean over every order in that region.
Exercise
A pivot table made with aggfunc="mean" and fill_value=0 shows 0 for North/B. Explain why this is misleading, and name two ways to avoid it.
Show answer
The North/B group has no valid units, so its mean is undefined (NaN). fillvalue=0 replaces it with 0, which looks like a measured average of zero units. Avoid it by omitting fillvalue so the NaN stays visible, or by filling after the fact with a clear marker such as table.fillna("n/a"). You can also use aggfunc="sum" if a total of zero is the honest answer.