Sub topic 6
When pivot fails: duplicate index and column pairs
This chapter assumes you know melt and pivot from the earlier chapters, and that you can use groupby with sum. It covers the most common pivot error and how to fix it.
Why pivot needs unique pairs
pivot places each value in one cell. The cell is chosen by two labels: the row label from index and the column label from columns. It does not combine values. If two source rows point to the same cell, pivot has no rule for choosing between them, so it stops.
Here store A has two rows for January:
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)The error is a ValueError. Its message starts with "Index contains duplicate entries, cannot reshape". The (A, jan) cell would have to hold both 60 and 40.
Finding the offending rows
Do not guess which rows collide. Ask pandas. duplicated with keep=False marks every row in a colliding group, not just the later ones.
clashes = sales[sales.duplicated(subset=["store", "month"], keep=False)]
print(clashes)This prints the two January rows for store A. Check them before you fix anything. Duplicates can be legitimate, such as two sales in one month. They can also be a data-entry mistake, such as the same record loaded twice.
Choosing a fix
The right fix depends on what the duplicates mean.
| Situation | Fix |
|---|---|
| Rows are separate events that should be combined | Aggregate with `pivot_table` and an `aggfunc` such as `"sum"` |
| Rows are accidental copies | Remove them with `drop_duplicates`, then use `pivot` |
| Another column tells the rows apart | Add that column to `index` or `columns` so each pair becomes unique |
For the sales data, the rows are separate sales, so summing is correct:
fixed = sales.pivot_table(
index="store",
columns="month",
values="sales",
aggfunc="sum",
)
print(fixed)month feb jan
store
A NaN 100.0
B 90.0 80.0Store A's January cell is now 60 + 40 = 100. Store A has no February row, so that cell is NaN. Because of the NaN, the columns become floats. The next chapters cover pivot_table and missing cells in detail.
Common mistakes
- Fixing the error by silently dropping rows.
drop_duplicateskeeps the first row of each group by default. This discards real data if the duplicates were distinct sales. - Checking the wrong columns. The test must use the same columns you pass to
indexandcolumns. If you pass a list toindex, include every column in that list. - Assuming the error will always appear.
pivotonly fails when the data has a collision. A pipeline can work for months and then break when a new duplicate arrives. Aduplicatedcheck before the reshape, or a deliberatepivot_table, makes the behavior predictable.
Exercise
A DataFrame has columns city, year and rain. Calling df.pivot(index="city", columns="year", values="rain") raises a ValueError. Write the line that shows every row involved in the problem, and name the call that gives each city and year the average rain.
Show answer
Use df[df.duplicated(subset=["city", "year"], keep=False)] to show all rows whose city and year pair repeats. Then use df.pivot_table(index="city", columns="year", values="rain", aggfunc="mean") to average the duplicates.