Sub topic 8
Handling missing cells and adding totals
This chapter assumes you can build a pivot_table with index, columns, values and aggfunc, and that you know how groupby aggregation works. It covers two options of pivot_table: fill_value for empty cells and margins for totals.
Why cells go missing
A pivot table has one cell for every pair of an index value and a column value. If the data has no rows for a pair, pandas has nothing to aggregate and leaves NaN.
The sample data below has two january rows for store A and no february row for store A.
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
plain = sales.pivot_table(
index="store", columns="month", values="sales", aggfunc="sum"
)
print(plain)The output is:
month feb jan
store
A NaN 100.0
B 90.0 80.0The NaN also turns the whole feb column into floats. That is why 90 prints as 90.0.
Filling cells with fill_value
Pass fill_value to replace the empty cells while the table is built.
filled = sales.pivot_table(
index="store", columns="month", values="sales",
aggfunc="sum", fill_value=0,
)
print(filled)month feb jan
store
A 0 100
B 90 80The columns can stay integers because no NaN remains. Calling plain.fillna(0) afterwards gives similar values, but the column dtype can stay float.
Adding totals with margins
Set margins=True to append a total row and a total column. Use margins_name to choose the label, which is "All" by default.
table = sales.pivot_table(
index="store", columns="month", values="sales",
aggfunc="sum", fill_value=0,
margins=True, margins_name="total",
)
print(table)month feb jan total
store
A 0 100 100
B 90 80 170
total 90 180 270The bottom-right cell, 270, is the grand total of the sales column.
Common errors with margins
- Totals use the original rows. pandas computes each margin from the underlying data, not from the cells you see. With
sumthe difference never shows. Withaggfunc="mean", the total is the mean of all matching rows. It is not the mean of the cell means. - Label collisions. If
"total"is already a value in the index or columns, the margin label clashes with it. Choose a name that does not occur in your data. - Total rows break later steps. A total row is a row like any other. If you later plot the table, sort it, or feed it to
melt, drop it first withtable.drop(index="total", columns="total"). - Mixing up
fill_valueandmargins. Fill values are inserted into empty cells. They do not change how the margins are computed.
Putting it together
A typical report-ready pattern is to aggregate, fill, add totals and restore a flat table. Flattening is covered in a later chapter, but the final step is short.
report = sales.pivot_table(
index="store", columns="month", values="sales",
aggfunc="sum", fill_value=0,
margins=True, margins_name="total",
).reset_index()
report.columns.name = None
print(report) store feb jan total
0 A 0 100 100
1 B 90 80 170
2 total 90 180 270In the printed output the third row's label is total, and store is now an ordinary column.
Exercise
Using the sales DataFrame above, build a pivot_table of the mean sales per store and month, with no fill value and with totals labelled "avg". Why is the "avg" value for store A in january 50.0, and what would the january total be?
Show answer
Use sales.pivot_table(index="store", columns="month", values="sales", aggfunc="mean", margins=True, margins_name="avg"). Store A has two january rows (60 and 40), so their mean is 50.0. The january total is the mean of all three january rows (60, 40 and 80), which is 60.0. It is not the mean of the cell means 50 and 80, which would be 65.0. The empty store A and february cell stays NaN because no fill_value was given.