Sub topic 11
What happens to the index
This chapter assumes you can build a DataFrame, select rows with loc and iloc, and have read the earlier chapters on duplicated(), drop_duplicates(), subset and keep. It covers what drop_duplicates() does to the row labels, what that breaks, and how to handle it.
The index keeps its old labels
A DataFrame's index is the set of labels attached to its rows. When drop_duplicates() removes rows, the surviving rows keep the labels they had. Pandas does not renumber them.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2, 3],
"customer": ["Ann", "Bob", "Bob", "Cy"],
"total": [10.0, 20.0, 20.0, 5.0],
})
unique = df.drop_duplicates()
print(unique.index.tolist()) # [0, 1, 3]
print(unique.loc[3, "customer"]) # Cy
print(unique.iloc[2]["customer"]) # Cy
try:
unique.loc[2]
except KeyError as exc:
print("KeyError:", exc) # KeyError: 2Row 2 was the duplicate, so the label 2 is gone. The index now has a gap. Label-based access (loc) and position-based access (iloc) give different answers for the same number. unique.loc[3] and unique.iloc[2] return the same row, and unique.loc[2] fails.
Renumbering with ignore_index
Pass ignore_index=True to get a fresh 0, 1, 2, ... index after the rows are removed.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2, 3],
"customer": ["Ann", "Bob", "Bob", "Cy"],
"total": [10.0, 20.0, 20.0, 5.0],
})
reindexed = df.drop_duplicates(ignore_index=True)
print(reindexed.index.tolist()) # [0, 1, 2]
print(reindexed.loc[2, "customer"]) # CyThe renumbering happens after duplicates are chosen. It does not change which rows are kept. It only relabels the result.
You can also call reset_index(drop=True) on any DataFrame. For a plain deduplication, the two forms give the same result.
import pandas as pd
df = pd.DataFrame({"a": [1, 1, 2]})
one = df.drop_duplicates(ignore_index=True)
two = df.drop_duplicates().reset_index(drop=True)
print(one.equals(two)) # TrueDo not forget drop=True. Without it, reset_index() keeps the old index and adds it as a new column. That column is called index when the old index had no name.
import pandas as pd
df = pd.DataFrame({"a": [1, 1, 2]})
print(df.drop_duplicates().reset_index().columns.tolist()) # ['index', 'a']When to renumber and when not to
A gapped index is not an error. Renumbering is useful in some cases and harmful in others.
| Situation | Better choice |
|---|---|
| Index is a default row counter with no meaning | `ignore_index=True` |
| You want to trace each surviving row back to its source row | Keep the old labels |
| Other Series or DataFrames are aligned to the original index | Keep the old labels |
| You will loop over `range(len(df))` and use `loc` | `ignore_index=True`, or switch to `iloc` |
| The index holds real identifiers such as order numbers | Keep it, and read the next section |
Keeping the old labels is a cheap audit trail. The labels of the removed rows are exactly the ones missing from the result.
import pandas as pd
df = pd.DataFrame({"k": [1, 2, 2, 3]})
unique = df.drop_duplicates()
removed = df.index.difference(unique.index)
print(removed.tolist()) # [2]Duplicate detection ignores the index
duplicated() and drop_duplicates() compare column values only. Two rows with different index labels but identical values count as duplicates.
import pandas as pd
s = pd.DataFrame({"a": [1, 1]}, index=["x", "y"])
print(s.duplicated().tolist()) # [False, True]This is harmless when the index is a row counter. It causes data loss when the index stores identifiers. Here each order has its own ID in the index, but orders 102 and 103 have the same customer and total.
import pandas as pd
orders = pd.DataFrame(
{"customer": ["Ann", "Bob", "Bob"], "total": [10.0, 20.0, 20.0]},
index=pd.Index([101, 102, 103], name="order_id"),
)
print(orders.drop_duplicates().index.tolist()) # [102 dropped? see below]The line above prints [101, 102]. Order 103 is removed even though it is a distinct order, because the index played no part in the comparison. Moving the identifier into a column fixes this.
import pandas as pd
orders = pd.DataFrame(
{"customer": ["Ann", "Bob", "Bob"], "total": [10.0, 20.0, 20.0]},
index=pd.Index([101, 102, 103], name="order_id"),
)
fixed = orders.reset_index().drop_duplicates()
print(fixed["order_id"].tolist()) # [101, 102, 103]Now order_id is an ordinary column, so it takes part in the comparison. All three rows are distinct. If you want to deduplicate on the identifier alone, use subset="order_id" after reset_index().
Duplicate index labels are a separate question
Rows can share an index label without being duplicate rows. The check for that lives on the index itself.
import pandas as pd
df = pd.DataFrame({"v": [10, 20, 30]}, index=["a", "b", "a"])
print(df.index.is_unique) # False
print(df.index.duplicated().tolist()) # [False, False, True]
print(df.loc["a"]["v"].tolist()) # [10, 30]
first_only = df[~df.index.duplicated(keep="first")]
print(first_only["v"].tolist()) # [10, 20]With a non-unique index, loc["a"] returns several rows, not one. Code that expects a single row can break in unexpected ways. Index.duplicated() takes the same keep options as the DataFrame method. You met this approach for column labels in the chapter on duplicate column labels.
The index after sorting and keeping the latest record
The "keep the latest record per key" pattern sorts first, so the index order often ends up scrambled.
import pandas as pd
events = pd.DataFrame({
"user": ["a", "a", "b"],
"updated": ["2026-01-01", "2026-02-01", "2026-01-15"],
"plan": ["free", "pro", "free"],
})
latest = (
events.sort_values("updated")
.drop_duplicates(subset="user", keep="last")
)
print(latest.index.tolist()) # [2, 1]The rows are in date order, and the labels are the original positions, so the index reads [2, 1]. You have three choices, depending on what you need.
import pandas as pd
events = pd.DataFrame({
"user": ["a", "a", "b"],
"updated": ["2026-01-01", "2026-02-01", "2026-01-15"],
"plan": ["free", "pro", "free"],
})
latest = (
events.sort_values("updated")
.drop_duplicates(subset="user", keep="last")
)
# 1. Restore the original row order, keeping the original labels.
print(latest.sort_index().index.tolist()) # [1, 2]
# 2. Renumber in date order.
print(latest.reset_index(drop=True).index.tolist()) # [0, 1]
# 3. Make the key the index.
print(latest.set_index("user").sort_index().index.tolist()) # ['a', 'b']Use ignore_index=True inside drop_duplicates() only if you want the renumbered, date-sorted result. Note that sort_index() restores the original order only because the labels were never reset.
Alignment surprises
Assigning a Series to a column aligns on index labels, not on position. After a deduplication that leaves gaps, a freshly built Series can misalign.
import pandas as pd
df = pd.DataFrame({"k": [1, 2, 2, 3]})
unique = df.drop_duplicates() # index [0, 1, 3]
unique["rank"] = pd.Series([1, 2, 3]) # labels 0, 1, 2
print(unique["rank"].tolist()) # [1.0, 2.0, nan]The new Series has labels 0, 1 and 2. The DataFrame has 0, 1 and 3. Label 3 finds no match and becomes NaN, and label 2 of the Series is dropped. You can avoid this in two ways. Reset the index before assigning, or assign plain values, such as a list or .to_numpy(), which are matched by position.
Verifying the index and the counts
After a cleanup, check the row count against the duplicate count, and check the index when you rely on it.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2, 3],
"customer": ["Ann", "Bob", "Bob", "Cy"],
"total": [10.0, 20.0, 20.0, 5.0],
})
clean = df.drop_duplicates(ignore_index=True)
assert len(df) - len(clean) == df.duplicated().sum()
assert not clean.duplicated().any()
assert clean.index.equals(pd.RangeIndex(len(clean)))
print(clean.shape) # (3, 3)If you kept the old labels, replace the last check with assert clean.index.is_unique, assuming the original index was unique.
Exercise
A DataFrame df has the index [0, 1, 2, 3, 4] and column name with values ["x", "y", "y", "z", "z"]. You run u = df.drop_duplicates(subset="name"). What is u.index.tolist()? Which call returns the label 3 row, u.loc[3] or u.iloc[3], and what happens with the other one? Finally, write the call that gives an index of [0, 1, 2] in one step.
Show answer
The default is keep="first", so rows 2 and 4 are removed and u.index.tolist() is [0, 1, 3]. u.loc[3] returns the row for "z". u.iloc[3] raises an IndexError, because u has only three rows and positions run from 0 to 2. The call is df.drop_duplicates(subset="name", ignore_index=True).
Exercise
A DataFrame orders uses order_id as its index. Rows 7 and 8 have the same customer and total. Why does orders.drop_duplicates() remove row 8, and how do you stop it?
Show answer
drop_duplicates() compares column values only and ignores the index, so row 8 looks like a repeat of row 7. Move the identifier into a column with orders.reset_index().drop_duplicates(), or choose the comparison columns explicitly with subset, including order_id.