Sub topic 11
What happens to the index
This chapter assumes you can create a DataFrame, select columns by label, and have used duplicated() and drop_duplicates() at a basic level. Here you will see what drop_duplicates() does to the row labels, why that matters, and how to control it.
The index keeps its original labels
The index is the set of row labels on the left of a DataFrame. When drop_duplicates() removes rows, the surviving rows keep the labels they had before. 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]Row 2 was the repeat of row 1, so it is gone. The labels 0, 1, and 3 remain, which leaves a gap where 2 used to be.
Why the gap matters
A gap is harmless for many tasks, and it can even help, because the labels still point back to the rows in the original data. The gap can cause trouble in two cases:
- Position versus label.
unique.loc[2]raises aKeyError, because label 2 no longer exists.unique.iloc[2]works, because it counts by position and returns the row labeled 3. - Code that assumes a clean range. Loops over
range(len(df))withloc, or exports that include the index, will behave unexpectedly when labels are not consecutive.
Renumbering with ignore_index
Pass ignore_index=True to get a fresh index from 0 to n-1.
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]This is the same as calling reset_index(drop=True) afterward, in one step. The drop=True part matters in the second form. Without it, reset_index() moves the old index into a new column instead of discarding it.
import pandas as pd
df = pd.DataFrame({"order_id": [1, 2, 2, 3]})
unique = df.drop_duplicates()
print(unique.reset_index(drop=True).index.tolist()) # [0, 1, 2]
print(unique.reset_index().columns.tolist()) # ['index', 'order_id']Choosing between the two
| Goal | Use |
|---|---|
| Keep a link to the original row positions | Default behavior |
| Get a clean 0 to n-1 index for later steps | `ignore_index=True` |
| Renumber after other filtering too | `reset_index(drop=True)` |
Common errors
- Reading the gap as a bug. Missing labels are expected after any row removal.
- Losing the audit trail too early. If you need to report which rows were removed, compare against the original index before you renumber. After
ignore_index=True, the original labels are gone. - Forgetting that the index is not compared.
duplicated()anddrop_duplicates()look at column values only, so two rows with different labels but identical values still count as duplicates.
Exercise
You run unique = df.drop_duplicates() and get an index of [0, 1, 3]. Why does unique.loc[2] fail, and what are two ways to get an index of [0, 1, 2]?
Show answer
Label 2 was the removed duplicate row, so no row has that label and loc raises a KeyError. You can get [0, 1, 2] by calling df.drop_duplicates(ignore_index=True), or by calling unique.reset_index(drop=True) afterward.