Sub topic 10
Removing Duplicate Rows with drop_duplicates
This chapter assumes you can write basic Python, build a pandas DataFrame, and select a column from it. It also assumes you have seen duplicated, which flags repeated rows and is the detection step that comes before removal. Here you will learn how drop_duplicates decides which rows to remove, which rows it keeps, and how it treats missing values and the index.
What drop_duplicates does
DataFrame.drop_duplicates returns a new DataFrame with repeated rows removed. It uses the same matching rule as duplicated. Two rows are duplicates when they hold equal values in every column you compare. By default, "every column" means all columns.
The method has four parameters you will use:
| Parameter | Default | Effect |
|---|---|---|
| `subset` | all columns | Column name or list of names used for the comparison |
| `keep` | `"first"` | Which member of each duplicate group survives: `"first"`, `"last"`, or `False` (none) |
| `ignore_index` | `False` | If `True`, the result gets a fresh index `0, 1, 2, ...` |
| `inplace` | `False` | If `True`, modifies the original and returns `None` |
The examples in this chapter use the table from earlier chapters. Each block defines it again so you can run any block on its own.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
is_dup = df.duplicated(subset=["city", "plan"])
print(is_dup.tolist()) # [False, False, True, False, True, False, False]
print(is_dup.sum()) # 2
deduped = df.drop_duplicates(subset=["city", "plan"])
print(deduped)
# city plan
# 0 Oslo free
# 1 Rome pro
# 3 Paris pro
# 5 Oslo pro
# 6 None free
print(len(df), len(deduped)) # 7 5Row 2 repeats row 0 (Oslo, free), and row 4 repeats row 1 (Rome, pro). Both are dropped. Row 5 (Oslo, pro) has the same city as rows 0 and 2 but a different plan, so it is not a duplicate on the pair.
The relationship to duplicated
drop_duplicates(...) is equivalent to selecting the rows where duplicated(...) is False:
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
a = df.drop_duplicates(subset=["city", "plan"])
b = df[~df.duplicated(subset=["city", "plan"])]
print(a.equals(b)) # TrueThis is useful in practice. Run duplicated first and inspect what would be removed, then call drop_duplicates with identical arguments. If the two calls use different subset or keep values, they will disagree.
Choosing which row to keep
The keep parameter matters whenever duplicates differ in columns outside subset. Here the rows are identical on the compared columns, so the choice only changes which index labels remain. With keep="last", the surviving rows are the later ones:
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
last = df.drop_duplicates(subset=["city", "plan"], keep="last")
print(last.index.tolist()) # [2, 3, 4, 5, 6]
none_kept = df.drop_duplicates(subset=["city", "plan"], keep=False)
print(none_kept.index.tolist()) # [3, 5, 6]keep=False removes every row that belongs to a duplicate group, including the first one. Rows 0, 1, 2 and 4 are all gone. Use it when you want only the rows that are unique on the chosen columns, for example to isolate records that appear exactly once.
Using keep=False to delete data is rarely what you want. It is better suited to finding the rows that were never repeated. To inspect the repeated groups instead, flag them with duplicated(keep=False) and sort:
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
repeated = df[df.duplicated(subset=["city", "plan"], keep=False)]
print(repeated.sort_values(["city", "plan"]))
# city plan
# 0 Oslo free
# 2 Oslo free
# 1 Rome pro
# 4 Rome proUsing subset to define "duplicate"
Without subset, every column must match. That is often too strict. If a table has an id and a loaded_at timestamp, two copies of the same record will differ in loaded_at, and a full-row comparison finds no duplicates. Choose the columns that identify a record.
Passing a single name as a string works, so subset="city" is valid. Applied to the example table, it keeps one row per distinct city:
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
one_per_city = df.drop_duplicates(subset="city")
print(one_per_city.index.tolist()) # [0, 1, 3, 6]
print(len(one_per_city)) # 4The result has 4 rows, which equals df["city"].nunique(dropna=False). This is a quick check that your deduplication matches your count of distinct values.
Missing values count as equal
Most comparisons in pandas treat a missing value as unequal to everything, including itself. Duplicate detection is an exception. Two missing values in the same column are considered the same value:
import pandas as pd
df2 = pd.DataFrame({
"city": [None, None, "Oslo"],
"plan": ["free", "free", "free"],
})
print(df2.duplicated().tolist()) # [False, True, False]
print(len(df2.drop_duplicates())) # 2The second row is dropped because it matches the first. This is usually the right behavior. It does mean that rows with unknown values can be merged even though the unknowns might refer to different real-world entities. If missing values should never be merged, deal with them first. You can filter them out with dropna, or give each one a distinct placeholder.
The index after removal
drop_duplicates keeps the original index labels of the surviving rows, so the result above has labels 0, 1, 3, 5, 6 with gaps. This is intentional, because the labels let you trace each row back to the source. It also causes trouble if later code assumes the labels are consecutive, for example .loc[2] raising KeyError.
Pass ignore_index=True to renumber the result, or call reset_index(drop=True):
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
clean = df.drop_duplicates(subset=["city", "plan"], ignore_index=True)
print(clean.index.tolist()) # [0, 1, 2, 3, 4]Common errors and gotchas
- Ignoring the return value.
df.drop_duplicates()on its own line does nothing todf. Assign the result, as indf = df.drop_duplicates(). Usinginplace=TruereturnsNone, sodf = df.drop_duplicates(inplace=True)replaces your DataFrame withNone. - Near-duplicates are not duplicates.
"Oslo","oslo"and"Oslo "are three different values. Normalize before comparing, for exampledf["city"] = df["city"].str.strip().str.lower(). - Wrong column names. A name in
subsetthat is not a column raisesKeyError. - Unhashable cells. Columns holding lists or dicts can raise
TypeError, because values must be hashable for the comparison. Convert them to tuples or strings first. - Choosing the survivor by position.
keep="first"means first in the current row order. If you want the most recent record per key, sort first, then keep the last:df.sort_values("updated_at").drop_duplicates("customer_id", keep="last"). - Silent data loss. Print
df.duplicated(subset=...).sum()before deleting, and compare lengths afterward.
Exercise
A DataFrame orders has columns customer_id, status and updated_at. Each customer appears several times, and you want exactly one row per customer: the one with the latest updated_at. Write the expression. Then say what orders.drop_duplicates("customer_id", keep=False) would return instead.
Show answer
orders.sort_values("updated_at").drop_duplicates("customer_id", keep="last"). Sorting puts each customer's latest row last in its group, and keep="last" retains it. The call with keep=False returns only the rows of customers who appear exactly once, because it drops every row in any duplicate group.
Exercise
A frame has 3 rows. Column a is [1, None, None] and column b is ["x", "y", "y"]. How many rows does drop_duplicates() return, and why?
Show answer
It returns 2 rows. Rows 1 and 2 are both (NaN, "y"). Duplicate detection treats missing values as equal, so row 2 is dropped as a repeat of row 1.