Sub topic 6
When pivot fails: duplicate index and column pairs
This chapter assumes you can build a DataFrame, select columns with [] and loc, and use groupby with aggregations such as sum and mean. It also assumes you have seen DataFrame.pivot turn long data into wide data. Here you will learn why pivot raises an error on some inputs, how to find the rows that cause it, and four ways to fix it.
What pivot requires
pivot reshapes without computing anything. For each pair of (index value, column value), it looks for one row and copies that row's values entry into the output cell. It never combines rows. That is why it needs the pair to be unique.
Take the call df.pivot(index="store", columns="month", values="sales"). Each (store, month) pair maps to exactly one cell in the result. If two rows share the same pair, they compete for one cell. pivot has no rule for choosing between them, and it does not guess. It raises a ValueError.
The rule is about the pair only. Other columns can repeat freely. Two rows with the same store and different months are fine. Two rows with the same store, the same month and the same sales value still fail, because the pair repeats.
Reproducing the error
The data below has two January rows for store A. They might be two separate sales batches, or a duplicate record from a data load.
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 output is:
pivot failed: Index contains duplicate entries, cannot reshapeThe message says "Index" because pivot builds a temporary index from the index and columns arguments. Then it calls unstack on that index. unstack requires the index to be unique. The error comes from that internal step, so you may see the same message when you call unstack directly.
Finding the duplicates
Before fixing anything, look at the rows that collide. The duplicated method with keep=False marks every member of a duplicate group. The default, keep="first", would hide the first row of each group. You want to see all of them.
keys = ["store", "month"]
clashes = sales[sales.duplicated(subset=keys, keep=False)]
print(clashes)The output is:
store month sales
0 A jan 60
1 A jan 40To see how large the problem is, count rows per pair:
counts = sales.groupby(keys).size()
print(counts[counts > 1])This lists only the pairs that occur more than once, with their counts. On real data this tells you whether you have a handful of stray rows or a structural problem, such as a missing key column.
Fix 1: remove the duplicates
If the extra rows are mistakes, delete them. drop_duplicates with subset keeps one row per pair. The keep argument chooses which one.
deduped = sales.drop_duplicates(subset=["store", "month"], keep="last")
print(deduped.pivot(index="store", columns="month", values="sales"))The output is:
month feb jan
store
A NaN 40.0
B 90.0 80.0Store A's January value is 40, the last row. The values became floats because store A has no February row, so that cell is NaN, and NaN forces a float column. Use this fix only when you know which row is correct. Dropping rows silently discards data, and "last" is only meaningful if the row order carries information.
Fix 2: aggregate with pivot_table
If the rows are legitimate and you want one number per cell, combine them. pivot_table does what pivot cannot: it groups by the index and columns, applies an aggregation function, then reshapes.
total = sales.pivot_table(
index="store", columns="month", values="sales", aggfunc="sum"
)
print(total)The output is:
month feb jan
store
A NaN 100.0
B 90.0 80.0Store A's January cell is now 100, the sum of 60 and 40. pivot_table is the usual answer to this error. The next chapter covers its options in detail. Here, the main point is that you must pick the aggregation.
Other useful choices are "first" and "last", which pick a row instead of combining rows. You can also pass "count" to see how many rows landed in each cell, or "max" and "min" for extremes.
pivot_table has a downside: it makes the error disappear. If duplicates come from a bug in your data pipeline, pivot_table with sum will quietly inflate your totals. With plain pivot, the error was a free data-quality check. If you expect unique keys, keep using pivot and let it fail.
Fix 3: aggregate first, then reshape
You can separate the two steps. groupby collapses the duplicates and produces a Series with a two-level index. Then unstack moves one level into columns.
indexed = sales.groupby(["store", "month"])["sales"].sum()
print(indexed.unstack("month"))The output is:
month feb jan
store
A NaN 100.0
B 90.0 80.0The result matches pivot_table. The two-step form is useful when you want to inspect or filter the grouped Series before reshaping, or when you need an aggregation that pivot_table handles awkwardly, such as a named aggregation on several columns. You will see unstack in more detail later in this tutorial.
Fix 4: make the key unique
Sometimes the rows are all real and you do not want to combine them. Both January values for store A should appear in the output. In that case your key is incomplete. Add a column that tells the duplicates apart. If the data has no natural one, number the rows within each group with cumcount:
numbered = sales.assign(n=sales.groupby(["store", "month"]).cumcount())
wide = numbered.pivot(index=["store", "n"], columns="month", values="sales")
print(wide)The output is:
month feb jan
store n
A 0 NaN 60.0
1 NaN 40.0
B 0 90.0 80.0Passing a list to index builds a two-level row index, which pivot supports in pandas 1.1 and later. Each (store, n, month) combination is now unique, so pivot succeeds. Store A has two rows, one for each January record. Use reset_index() afterward if you want store and n back as ordinary columns.
The number n is only a label for the position within the group. It has no business meaning, so avoid treating it as data. If the data has a real distinguishing column such as a date, an order ID or a region, use that instead of n.
Choosing a fix
| Situation | Fix | Risk |
|---|---|---|
| Rows are accidental copies | `drop_duplicates(subset=keys)` | Loses data if the rows were not true copies |
| Rows are real, one number per cell is wanted | `pivot_table` with an explicit `aggfunc` | Hides data-quality problems |
| You want to inspect the grouped data first | `groupby(...).agg(...).unstack()` | More code than `pivot_table` |
| Rows are real, all must be kept | Add a distinguishing column to `index` | Extra index level in the output |
Other causes of the same error
The cause is not always an obvious double record. Check these cases when the error surprises you:
- Case or whitespace differences.
"jan"and"Jan"are different values and do not collide, but a cleaning step that lowercases the column afterward can create collisions you did not have before. Clean keys before you pivot. - A missing key column. If your data has one row per store, month and product, pivoting on store and month alone makes every product collide. Filter to one product, or aggregate over product on purpose.
- A failed or repeated concatenation. Calling
pd.concaton overlapping frames, or running a load step twice, duplicates whole rows.sales.duplicated().sum()catches full-row duplicates quickly. - Missing values in keys. Rows with
NaNin an index or columns key are handled differently across functions and versions. Drop or fill them first, so the shape of the result does not depend on howNaNis treated.
A guard you can reuse
When you expect unique pairs, make the expectation explicit and give a better message than pandas does:
def checked_pivot(df, index, columns, values):
keys = [index, columns] if isinstance(index, str) else [*index, columns]
dup = df.duplicated(subset=keys, keep=False)
if dup.any():
raise ValueError(
f"{int(dup.sum())} rows share a key on {keys}:\n{df[dup]}"
)
return df.pivot(index=index, columns=columns, values=values)
try:
checked_pivot(sales, "store", "month", "sales")
except ValueError as err:
print(err)The output is:
2 rows share a key on ['store', 'month']:
store month sales
0 A jan 60
1 A jan 40This version names the offending rows in the message, so you can start fixing the problem without a separate inspection step.
Summary of the failure
pivot is a pure rearrangement. It needs one row for each (index, columns) pair and raises ValueError: Index contains duplicate entries, cannot reshape when it finds more. Find the colliding rows with duplicated(subset=..., keep=False). Then decide what the duplicates mean, and pick one of four fixes: drop them, aggregate them with pivot_table, aggregate them with groupby and unstack, or extend the key so they stop colliding.
Exercise
The DataFrame orders has columns customer, day and amount. It has three rows for customer "Ana" on day "mon" with amounts 5, 7 and 9. Calling orders.pivot(index="customer", columns="day", values="amount") raises a ValueError. Name the cause, then write a call that gives Ana's Monday cell the total of her orders, and say what Ana's Monday cell would show if you wrote the call without aggfunc.
Show answer
The pair ("Ana", "mon") appears three times, and pivot cannot choose one value for one cell. Use orders.pivot_table(index="customer", columns="day", values="amount", aggfunc="sum"), which puts 21 in Ana's Monday cell. Without aggfunc, the default is "mean", so the cell would show 7.0, which is the average of 5, 7 and 9 and not the total.
Exercise
You run pivot_table with aggfunc="sum" on a table that should have one row per store and month, and the January total for store A is twice what you expected. Why can this happen, and which function should you have used while checking the data?
Show answer
The table probably contains the same record twice, for example from a data load that ran two times. pivot_table sums both copies without any warning. Plain pivot would have raised a ValueError and exposed the problem. You can also check first with df.duplicated(subset=["store", "month"], keep=False).