Sub topic 9
Dropping duplicates with drop_duplicates()
This chapter assumes you can build a DataFrame, select columns by label, and read a boolean mask. It also assumes you have seen duplicated(), which flags repeated rows.
What drop_duplicates() does
drop_duplicates() returns a new DataFrame that has no repeated rows. By default, a row counts as a duplicate when every column matches an earlier row. The first occurrence stays and later copies are removed.
A first example
Check the count first, then remove the repeats.
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],
})
print(df.duplicated().tolist()) # [False, False, True, False]
print(df.duplicated().sum()) # 1
unique = df.drop_duplicates()
print(df.shape, unique.shape) # (4, 3) (3, 3)
print(unique.index.tolist()) # [0, 1, 3]Row 2 was a copy of row 1, so it is gone. The original df is unchanged, and unique holds the result.
The index keeps its old labels
Look at unique.index.tolist(). It is [0, 1, 3], not [0, 1, 2]. drop_duplicates() keeps each surviving row's original label, so the index now has a gap.
That is often fine, and it lets you trace each row back to the source data. If you want a clean 0, 1, 2 sequence, pass ignore_index=True.
reindexed = df.drop_duplicates(ignore_index=True)
print(reindexed.index.tolist()) # [0, 1, 2]Behavior to know about
- Rows are compared by value, not by index label. Two rows with different labels but identical values are duplicates.
- Missing values (
NaN) are treated as equal to each other. Two rows that are identical except for matchingNaNcells are therefore duplicates. - The comparison is exact.
"Ann"and"ann "are different values, so they survive. You will normalize such values before deduplicating in a later chapter. - Row order is preserved. The method never sorts your data.
Check before and after
Make it a habit to confirm that the number of rows removed matches the number you flagged.
n_flagged = df.duplicated().sum()
cleaned = df.drop_duplicates()
assert len(df) - len(cleaned) == n_flagged
print(f"Removed {n_flagged} duplicate row(s); {len(cleaned)} remain.")If the counts differ from what you expected, the usual cause is that your definition of "duplicate" is narrower or wider than "every column matches". The next chapter covers subset and keep, which let you change that definition.
Summary table
| Task | Call |
|---|---|
| Count repeated rows | `df.duplicated().sum()` |
| Remove repeated rows | `df = df.drop_duplicates()` |
| Remove and renumber | `df = df.drop_duplicates(ignore_index=True)` |
Exercise
A DataFrame has 100 rows and df.duplicated().sum() returns 12. You run df.drop_duplicates(ignore_index=True) without assigning the result. What is len(df) afterward, and what would the returned object's index end at if you had kept it?
Show answer
len(df) is still 100, because the method returns a new DataFrame and leaves the original unchanged. The returned object would have 88 rows, and ignore_index=True would number them 0 to 87.
Exercise
You run unique = df.drop_duplicates() and unique.index.tolist() shows [0, 1, 3, 4, 7]. Why are labels missing, and how do you get 0 to 4?
Show answer
The rows with labels 2, 5, and 6 were duplicates and were removed. The remaining rows kept their original labels. Use df.drop_duplicates(ignore_index=True), or call unique.reset_index(drop=True).