Sub topic 3
Handling missing cells and adding totals
Assume you know basic pandas selection, groupby, and aggregation. This chapter focuses on reshaping tables after those operations.
Fill missing cells and add totals
pivot_table can aggregate duplicate keys and control empty cells. Use fill_value to replace missing combinations and margins=True to add totals.
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",
fill_value=0,
margins=True,
margins_name="total",
)
print(table)Store A has no February row, so fill_value=0 supplies zero. The total row and column contain sums.
> callout note > Use fill_value only when a missing combination means zero. If it means “unknown,” leave it missing or handle it separately. > ```
Read and flatten MultiIndex columns
Multiple aggregation functions create hierarchical column labels called a MultiIndex.
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)The resulting names include sum_jan and count_feb. reset_index() moves the store index back into an ordinary column.
Move index levels with `stack` and `unstack`
unstack moves an index level into columns. stack performs the reverse operation.
indexed = sales.groupby(["store", "month"])["sales"].sum()
wide = indexed.unstack("month")
long_again = wide.stack()
print(wide)
print(long_again)Use these methods when the data already has meaningful index levels.
Related reshaping tools
| Tool | Main use |
|---|---|
| `wide_to_long` | Split repeated column prefixes into rows |
| `crosstab` | Count combinations of categories |
wide_to_long handles structured column groups:
scores = pd.DataFrame({
"id": [1, 2],
"score_math": [90, 80],
"score_art": [70, 60],
})
tidy = pd.wide_to_long(
scores, stubnames="score", i="id", j="subject",
sep="_", suffix=r"\w+"
).reset_index()
print(tidy)crosstab counts category combinations:
counts = pd.crosstab(sales["store"], sales["month"])
print(counts)Exercise
Which argument adds a total row and column to a pivot table?
Show answer
Use margins=True, optionally with margins_name to choose the label.