Sub topic 7
Aggregating while reshaping with pivot_table
The previous chapter showed that pivot fails when two rows share the same index and column pair. pivot_table handles that case. It groups the rows, applies an aggregation function to each group, and lays the results out as a grid.
This chapter assumes you can build and index a DataFrame, and that you know groupby with aggregations such as sum and mean. It also assumes you have met the ValueError that pivot raises on duplicate keys.
What pivot_table does
pivot_table is a groupby followed by an unstack, packaged in one call. It takes three kinds of input:
index: the column (or columns) whose values become the row labels.columns: the column (or columns) whose values become the column labels.values: the column (or columns) to aggregate and place in the cells.
An aggfunc argument says how to combine rows that fall into the same cell.
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
table = sales.pivot_table(
index="store",
columns="month",
values="sales",
aggfunc="sum",
)
print(table)Store A has two january rows, 60 and 40, so the January cell for A holds their sum, 100. Store A has no february row, so that cell is NaN. The output looks like this:
month feb jan
store
A NaN 100
B 90.0 80The feb column holds floats because NaN is a float value. The jan column stays integer because it has no gaps.
Comparing pivot and pivot_table
The two functions overlap, but they are built for different jobs.
| Feature | `pivot` | `pivot_table` |
|---|---|---|
| Duplicate index and column pairs | Raises `ValueError` | Aggregates them |
| Aggregation | None | `aggfunc`, default `"mean"` |
| Several `values` columns | Supported | Supported |
| Missing cells | `NaN` | `NaN`, or `fill_value` |
| Totals | Not available | `margins=True` |
| Typical use | Reshape data that is already unique | Summarize data while reshaping |
Use pivot when each pair is unique and you want an error if that assumption breaks. Use pivot_table when you expect several rows per pair, or when you want a summary rather than a straight rearrangement.
Choosing aggfunc
The default is the mean. If you leave out aggfunc, the result silently averages duplicates. In the example above, A's January cell would be 50.0 instead of 100. That is correct for a rate or a price, but wrong for a quantity you meant to add up. Always write aggfunc explicitly.
aggfunc accepts several forms:
- A string name such as
"sum","mean","count","min","max","median","first"or"nunique". - A function, such as
numpy.sumor your own function that takes a Series and returns one value. - A list of any of these, which produces one block of columns per function.
- A dictionary that maps each
valuescolumn to its own function or list.
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
mean_table = sales.pivot_table(
index="store", columns="month", values="sales", aggfunc="mean"
)
print(mean_table)The output is:
month feb jan
store
A NaN 50.0
B 90.0 80.0Compare it with the sum table above. The same data gives different answers depending on aggfunc. The grid layout does not tell you which function was applied, so name it in your column labels or in a comment.
Counting rows versus counting values
The "count" function counts non-null entries in the values column. It does not count rows. If sales contained a NaN, that row would not be counted. To count rows regardless of nulls, use "size":
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
counts = sales.pivot_table(
index="store", columns="month", values="sales", aggfunc="size"
)
print(counts)The row for A shows 2 in jan and NaN in feb. Here the NaN means no rows exist for that pair at all, which is different from a count of zero. The next chapter covers filling those cells.
Several values and several functions
Pass a list to values to aggregate more than one column. Pass a list or dictionary to aggfunc to use more than one function. Both create MultiIndex columns, where each column label has two or more levels.
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
"units": [6, 4, 8, 9],
})
wide = sales.pivot_table(
index="store",
columns="month",
values=["sales", "units"],
aggfunc={"sales": "sum", "units": "mean"},
)
print(wide.columns.tolist())This prints:
[('sales', 'feb'), ('sales', 'jan'), ('units', 'feb'), ('units', 'jan')]The first level is the original value column and the second level is the columns key. The dictionary lets sales be added up while units is averaged. A later chapter shows how to flatten these tuples into plain names.
Grouping on several keys
index and columns both accept lists. Each additional key adds a level to the row labels or column labels.
import pandas as pd
orders = pd.DataFrame({
"region": ["N", "N", "N", "S", "S"],
"store": ["A", "A", "B", "C", "C"],
"month": ["jan", "feb", "jan", "jan", "feb"],
"sales": [10, 20, 30, 40, 50],
})
nested = orders.pivot_table(
index=["region", "store"],
columns="month",
values="sales",
aggfunc="sum",
)
print(nested)The result has a two-level row index of region and store. Rows are sorted by those keys. Store B has no february row, so its feb cell is NaN. Call reset_index() if you want region and store back as ordinary columns.
Omitting columns
You can leave out columns entirely. The result then has one column per value, with one row per group. This is a groupby written in pivot syntax.
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
totals = sales.pivot_table(index="store", values="sales", aggfunc="sum")
print(totals)The output is:
sales
store
A 100
B 170The groupby equivalent
Knowing the equivalent groupby code helps you debug a result and choose between the two. The following code produces the same grid as the first example in this chapter:
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
same = sales.groupby(["store", "month"])["sales"].sum().unstack("month")
print(same)Reach for pivot_table when the grid is the goal and you want options such as fill_value and margins. Reach for groupby when you need named aggregations, several different statistics on one column, or a long result that you do not plan to spread out.
Common mistakes
- Relying on the default mean. Duplicates are averaged without any warning. Write
aggfunc="sum"if you mean a total. - Omitting
values. Pandas then aggregates every column that is not a key. A text column with the default mean can raise an error or add unwanted columns. List the columns you want. - Expecting missing key combinations to be zero. They are
NaN. Asumover no rows is not computed at all, because no group exists. - Losing rows with missing keys. Rows where an
indexorcolumnsvalue isNaNare dropped from the result, as ingroupby. Check for them withisna()before reshaping if the totals matter. - Assuming the order of columns. Labels are sorted alphabetically, so
febappears beforejan. Reindex the columns if you need calendar order. - Forgetting the index. The key columns become the row index and the column axis gets a name. Call
reset_index()and clearcolumns.namewhen you need a flat table.
Practice
Exercise
A DataFrame df has columns team, quarter and points. Some teams have several rows for the same quarter. Write a pivot_table call that gives one row per team, one column per quarter, and the total points in each cell. What happens to a team that has no rows in a given quarter?
Show answer
Use df.pivot_table(index="team", columns="quarter", values="points", aggfunc="sum"). A team with no rows in a quarter gets NaN in that cell, because no group exists for that pair. Without aggfunc="sum" the cells would hold means.
Exercise
You run df.pivot_table(index="store", columns="month", values="sales") and the numbers are half the totals you expected. Name the cause and the fix.
Show answer
The default aggfunc is the mean, so each cell averages two rows instead of adding them. Add aggfunc="sum".