Sub topic 8
Handling missing cells and adding totals
This chapter assumes you can build a pivot_table with an aggfunc, as in the previous chapter. It covers two things that follow from that. First, wide tables often contain empty cells, and you need to decide what they mean. Second, you often want totals added, and you need to know how those totals are computed.
Where missing cells come from
A pivot has one cell for every combination of an index value and a column value. If the long data has no row for a combination, that cell has nothing to show. Pandas fills it with NaN, which stands for "not a number" and marks a missing value.
Here is the long data used in this chapter. Store A sold nothing in February, and January has two rows 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],
})
raw = sales.pivot_table(
index="store",
columns="month",
values="sales",
aggfunc="sum",
)
print(raw)month feb jan
store
A NaN 100.0
B 90.0 80.0The two January rows for store A were summed to 100. The February cell for store A is NaN because no row exists for that pair. Because NaN is a float value, pandas also converted the integer sales into floats.
Two kinds of "missing"
A NaN in the pivot can mean different things, and the right fix depends on which one you have.
| Situation | What it means | Typical fix |
|---|---|---|
| No row exists for the pair | Nothing was recorded, and for counts or sums that often means zero | `fill_value=0` |
| A row exists but its value is `NaN` | The measurement is unknown | Usually leave it, or fill with a stated default |
| Every value in a column is `NaN` | Nothing to aggregate | `pivot_table` drops that column unless you pass `dropna=False` |
Filling with zero is correct for a sum of sales when "no row" means "no sales". It is wrong for a mean temperature, because a missing temperature is not zero degrees. Decide what the gap means before you fill it.
Filling with fill_value
The fill_value argument replaces NaN cells in the result.
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 80Because no NaN values remain, the columns can be integers again. Compare the alternative of calling fillna on the finished table.
alt = raw.fillna(0).astype(int)
print(alt)Both give the same table. Use fill_value when you are already calling pivot_table. Use fillna when you need a different fill per column, such as raw.fillna({"feb": 0, "jan": -1}), or when the table came from pivot, which has no fill_value argument.
Adding totals with margins
A margin is a row or column of totals placed at the edge of the table. Pass margins=True to add a total row and a total column. By default the label is All. The margins_name argument changes it.
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 is the grand total, 270. It equals the sum of all four original rows.
The diagram shows a detail that matters. The margins are computed from the original rows, not from the cells you can see in the table. For a sum, the two approaches agree. For other functions, they do not.
Margins are not averages of the cells
Switch the aggregation to mean and the difference shows.
means = sales.pivot_table(
index="store",
columns="month",
values="sales",
aggfunc="mean",
margins=True,
)
print(means)month feb jan All
store
A NaN 50.0 50.0
B 90.0 80.0 85.0
All 90.0 60.0 67.5Check the January total of 60. It is the mean of the three January rows (60, 40 and 80), not the mean of the two visible cells (50 and 80), which would be 65. The grand total 67.5 is the mean of all four rows. Each margin answers the question "what is this aggregate over all underlying rows in this row or column?"
This is usually what you want, but it surprises people who check the totals by hand. If you want the mean of the cells, build the margin yourself, as shown in the next section.
Building totals by hand
Sometimes margins=True does not fit. You may want only a total column, a total that differs from the underlying-row rule, or a total on a table that came from pivot. In those cases, compute the sums directly.
manual = raw.fillna(0)
manual["total"] = manual.sum(axis=1)
manual.loc["total"] = manual.sum()
print(manual)month feb jan total
store
A 0.0 100.0 100.0
B 90.0 80.0 170.0
total 90.0 180.0 270.0Order matters here. The total column is added first, so the second sum() includes it, and the bottom-right cell becomes the grand total. If you add the row first and then the column, you get the same result. If you add both from the same original table, the corner cell is wrong or empty.
The axis=1 argument sums across columns for each row. The default axis=0 sums down each column.
Gotchas with margins
- Name collisions. If
margins_namematches an existing label in the index or columns, pandas raises aValueError. A store literally named"All"is the usual cause. Pick a differentmargins_name. - Several aggregation functions. With a list such as
aggfunc=["sum", "count"], each function gets its own margin. The columns are a MultiIndex, so flatten them before you rely on names liketotal. - Fill and margins together.
fill_valuereplaces empty cells in the body of the table. The margins are still computed from the original rows, so a filled zero does not drag down a mean. - Totals are data now. A table with a
totalrow mixed into the index is convenient to read but awkward to process. If you plan to melt, plot, or filter the result, drop the margins first withtable.drop(index="total", columns="total").
Counting missing cells
Before you fill anything, find out how many cells are empty. This tells you whether the data is sparse enough to need a different design.
print("empty cells:", int(raw.isna().sum().sum()))
print("share empty:", raw.isna().to_numpy().mean())empty cells: 1
share empty: 0.25The first sum() counts the empty cells in each column. The second adds those counts together. The second line takes the mean of a True/False array, which gives the fraction of cells that are empty. If most of a wide table is empty, the long layout is often the better format for that data.
Choosing a fill strategy
- Ask what "no row" means. For counts and sums, it usually means zero.
- Fill with
fill_valueinsidepivot_table, or withfillnaafterwards if you need per-column control. - Add totals last, either with
margins=Trueor by hand. - Check one margin against the original data, especially when the aggregation is not a sum.
Exercise
Using the sales DataFrame from this chapter, build a table with aggfunc="sum", margins=True and the default margin name, but without fill_value. What does the February cell for store A show, and what does the All row show for February?
Show answer
Store A's February cell is NaN, because no row exists for that pair. The All row for February is 90, because margins are computed from the original rows and the only February row is store B's 90. The missing cell does not make the margin NaN.
Exercise
A pivot table of mean temperature by city and month has empty cells where no readings were taken. A colleague passes fill_value=0. Why is this a problem, and what is a safer approach?
Show answer
Zero degrees is a real temperature, so the filled cells look like measurements and would distort later averages or charts. A safer approach is to leave the cells as NaN, or fill them with an explicit marker only at the display step, keeping an unfilled copy for calculations.
Exercise
Why does sales.pivot_table(index="store", columns="month", values="sales", aggfunc="mean", margins=True) show 60.0 for the January margin instead of 65.0, the mean of the two visible January cells?
Show answer
Margins are computed from the underlying rows, not from the displayed cells. January has three rows (60, 40 and 80), and their mean is 60.0. The visible cells are 50 (the mean of store A's two rows) and 80, and their mean of 65 weights each store equally rather than each row.