Sub topic 7
What counts as a duplicate row
This chapter assumes you can create a DataFrame, select columns by label, and read basic Python dictionaries and lists. It defines "duplicate" before you use duplicated() and drop_duplicates() in the next chapters.
The working definition
pandas treats two rows as duplicates when they have equal values in every column being compared. By default it compares all columns. The index label is not part of the comparison, so rows 1 and 2 below are duplicates even though their labels differ.
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]The first time a row appears, pandas does not call it a duplicate. Only later repeats are flagged. This matters when you decide which copy to keep.
Whole-row and key-based duplicates
A duplicate depends on which columns you compare. Two rows can be duplicates on order_id alone but differ elsewhere.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2],
"customer": ["Ann", "Bob", "Bobby"],
})
print(df.duplicated().sum()) # 0
print(df.duplicated(subset="order_id").sum()) # 1The first call compares both columns, so no rows match. The second compares only order_id, so row 2 is flagged. Which definition is right depends on your data. An order ID is usually meant to be unique, so a repeated ID with different names signals a data problem. A fully identical row is usually an accidental copy.
What pandas considers equal
Equality follows a few rules that can surprise you.
- Missing values match each other. Two rows with
NaNin the same column count as equal there, unlike normalNaN == NaNcomparison. - Case and whitespace matter.
"Ann","ann"and"Ann "are three different values. - Types matter less than you might expect for numbers.
1and1.0compare as equal, but the string"1"does not equal the integer1.
import pandas as pd
import numpy as np
df = pd.DataFrame({
"name": ["Ann", "ann", "Ann ", "Ann", None, None],
"score": [1, 1, 1, 1, np.nan, np.nan],
})
print(df.duplicated().tolist())
# [False, False, False, True, False, True]Row 3 matches row 0 exactly. Rows 1 and 2 differ only by case and a trailing space, so they are kept as separate values. Rows 4 and 5 both hold missing values, so row 5 is flagged.
Deciding before you delete
Before removing anything, answer two questions:
- Which columns together identify "the same record" in this dataset?
- If two rows match, is it safe to lose one of them, and which one should stay?
Write the answers down as a list of column names. You will pass that list to subset in the next chapters.
Exercise
A DataFrame has columns email and signup_date. Rows 0 and 1 have email "[email protected]" with different signup dates. Does df.duplicated() flag row 1? Does df.duplicated(subset="email") flag it?
Show answer
df.duplicated() does not flag row 1, because the signup dates differ and all columns are compared. df.duplicated(subset="email") does flag row 1, because only the email column is compared and row 0 is the first occurrence with that email.
Exercise
A column holds the values "Cy", "cy" and "Cy". Which of these rows are flagged by duplicated() on that column alone?
Show answer
Only the third row is flagged. It exactly matches the first. "cy" differs by case, so it counts as a distinct value.