Sub topic 7
Aggregating while reshaping with pivot_table
This chapter assumes you can build a DataFrame, use groupby with sum and count, and know what pivot does. It also assumes you have seen pivot fail on duplicate keys. pivot_table handles those duplicates by aggregating them.
Why pivot_table exists
pivot only rearranges values. Each (index, column) pair must appear at most once, because there is nowhere to put a second value. Real data often breaks this rule, for example when several sales rows exist for the same store and month.
pivot_table combines a groupby with a reshape. It groups rows by the index and column keys, applies an aggregation function to each group, and lays out the results in a grid.
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
try:
sales.pivot(index="store", columns="month", values="sales")
except ValueError as err:
print("pivot failed:", err)Store A has two rows for january, so pivot raises a ValueError.
The basic call
table = sales.pivot_table(
index="store",
columns="month",
values="sales",
aggfunc="sum",
fill_value=0,
margins=True,
margins_name="total",
)
print(table)Each argument has a role:
| Argument | Role |
|---|---|
| `index` | Column whose values become the row labels |
| `columns` | Column whose values become the column labels |
| `values` | Column to aggregate |
| `aggfunc` | How to combine rows that share a cell |
| `fill_value` | Replacement for cells with no data |
| `margins` | Adds a total row and column when `True` |
| `margins_name` | Label used for those totals |
In the result, store A's january cell is 100 (60 + 40). Store A has no february rows, so that cell would be NaN. Here fill_value=0 replaces it with 0. The total row and column hold the sums across each axis.
Choosing aggfunc
The default aggfunc is "mean". If you forget to set it, duplicate rows are averaged, not summed. This is a common source of wrong totals.
You can pass a string such as "sum", "count", "max", or any callable. A list of functions computes several aggregations at once.
multi = sales.pivot_table(
index="store",
columns="month",
values="sales",
aggfunc=["sum", "count"],
)
multi.columns = ["_".join(map(str, col)) for col in multi.columns]
multi = multi.reset_index()
print(multi)A list of functions produces two-level column labels, such as ("sum", "jan"). The list comprehension joins each pair into one name, such as sum_jan or count_feb. The final reset_index turns store back into an ordinary column. Later chapters cover MultiIndex columns in more detail.
Common errors
- Averages where you expected totals. The default is
mean. Always setaggfuncexplicitly. - Missing cells treated as zero by accident.
fill_value=0hides the difference between "no rows" and "rows that sum to zero". Leave it out if that difference matters. - Rows silently dropped. By default
pivot_tabledrops rows where the key columns areNaN. Check for missing keys first. - Using
pivot_tableto hide bad data. If duplicates should not exist,pivotfailing is useful. Switch topivot_tableonly when aggregating is the intended behavior.
Exercise
Exercise
A DataFrame has columns region, product and revenue, with several rows per region and product pair. You call df.pivot_table(index="region", columns="product", values="revenue") and the cell values look too small. What is the likely cause, and how do you fix it?
Show answer
The default aggfunc is "mean", so duplicate rows were averaged instead of summed. Add aggfunc="sum" to the call. Optionally add fill_value=0 for empty cells.
Exercise
Using the sales DataFrame above, write a pivot_table call that counts the rows in each store and month cell and shows 0 where there are none.
Show answer
sales.pivottable(index="store", columns="month", values="sales", aggfunc="count", fillvalue=0)