Sub topic 10
Removing duplicate rows with drop_duplicates
This chapter assumes you can build a DataFrame, select columns, and have read the previous chapter on duplicated. Here you will remove the rows that duplicated flags.
What drop_duplicates does
DataFrame.drop_duplicates returns a new DataFrame with repeated rows removed. It uses the same rules as duplicated, so you can preview what it will remove by counting duplicated results first. The original DataFrame is not changed.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
print(df.duplicated(subset=["city", "plan"]).sum()) # 2 rows would be removed
deduped = df.drop_duplicates(subset=["city", "plan"])
print(deduped)
print(len(df), len(deduped)) # 7 5The result keeps rows 0, 1, 3, 5 and 6. Rows 2 and 4 repeat the (city, plan) pairs of rows 0 and 1, so they are dropped.
Choosing the columns with subset
By default, a row counts as a duplicate only if every column matches. The subset argument limits the comparison to the columns you name. Other columns are ignored when deciding, but they stay in the result.
by_city = df.drop_duplicates(subset="city")
print(by_city) # one row per city, including one row for the missing valueThis keeps one row per distinct city: Oslo, Rome, Paris and the missing value. Choose subset to match what "the same record" means in your data. For example, two orders with the same order_id are duplicates even if their timestamps differ.
Choosing which row survives with keep
The keep argument controls which member of each duplicate group stays.
| keep value | Result |
|---|---|
| `"first"` (default) | Keeps the first occurrence, drops later ones |
| `"last"` | Keeps the last occurrence, drops earlier ones |
| `False` | Drops every row that has a duplicate, keeping only rows that occur once |
last = df.drop_duplicates(subset=["city", "plan"], keep="last")
only_unique = df.drop_duplicates(subset=["city", "plan"], keep=False)
print(last.index.tolist()) # [2, 3, 4, 5, 6]
print(only_unique.index.tolist()) # [3, 5, 6]Use keep="last" when later rows are newer and you want the latest version. Use keep=False when you want to remove ambiguous records entirely.
Tidying the index
Removing rows leaves gaps in the index, as the [0, 1, 3, 5, 6] labels above show. Pass ignore_index=True to renumber the result from 0.
clean = df.drop_duplicates(subset=["city", "plan"], ignore_index=True)
print(clean.index.tolist()) # [0, 1, 2, 3, 4]Common errors
- Expecting the original to change.
df.drop_duplicates()on its own line discards the result. Assign it:df = df.drop_duplicates(). - Dropping on too few columns.
subset="city"removes rows that differ inplan. Check withduplicated(subset=...)first. - Confusing keep=False with "no deduplication". It removes all copies, including the first one.
- Relying on the old index. Labels from the original DataFrame persist unless you use
ignore_index=Trueor callreset_index(drop=True).
Exercise
Using the DataFrame above, write code that keeps only the most recent row (the last one) for each city, and returns a result with an index numbered from 0. How many rows remain?
Show answer
result = df.dropduplicates(subset="city", keep="last", ignoreindex=True). Four rows remain: Paris, Rome, Oslo (row 5) and the missing city (row 6).