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 know that duplicated() returns one True or False per row. Here you will use drop_duplicates() to remove repeated rows and learn how it decides what counts as a repeat.
What the method does
DataFrame.drop_duplicates() returns a new DataFrame with repeated rows removed. By default it compares every column. A row is dropped only when all of its values match a row that appeared earlier. The first occurrence stays.
The method is a thin layer over duplicated(). Internally it builds the same boolean mask and keeps the rows where the mask is False. This code shows it on a small orders table:
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],
})
mask = df.duplicated()
print(mask.tolist()) # [False, False, True, False]
unique = df.drop_duplicates()
print(unique)
print(df.shape, unique.shape)The output is:
order_id customer total
0 1 Ann 10.0
1 2 Bob 20.0
3 3 Cy 5.0
(4, 3) (3, 3)Row 2 is gone because it matches row 1 in every column. Notice that the index still reads 0, 1, 3. The method removes rows but does not renumber the ones that remain. The chapter on the index covers this, and the section on ignore_index below gives a short preview.
The signature
The full signature is:
DataFrame.drop_duplicates(subset=None, *, keep="first", inplace=False, ignore_index=False)All four arguments are optional, and the table lists them:
| Argument | Default | Effect |
|---|---|---|
| `subset` | `None` (all columns) | A column label or list of labels to compare instead of the whole row |
| `keep` | `"first"` | `"first"` keeps the first occurrence, `"last"` keeps the last, `False` drops every member of a duplicate group |
| `inplace` | `False` | Modify the original object and return `None` |
| `ignore_index` | `False` | Renumber the result 0, 1, 2, ... |
The next chapter covers subset and keep in detail. This chapter focuses on the default behavior and on what "the same" means.
The result is a new object
Like most pandas methods, drop_duplicates() does not change the original DataFrame. If you call it and discard the return value, nothing happens:
import pandas as pd
df = pd.DataFrame({"a": [1, 1, 2], "b": ["x", "x", "y"]})
df.drop_duplicates() # result is thrown away
print(len(df)) # 3
df = df.drop_duplicates() # assign it back
print(len(df)) # 2The inplace=True option does modify the original, but it returns None. That causes a second bug when you write df = df.drop_duplicates(inplace=True), because df becomes None:
import pandas as pd
df = pd.DataFrame({"a": [1, 1, 2]})
returned = df.drop_duplicates(inplace=True)
print(returned) # None
print(len(df)) # 2How "equal" is decided
Two rows are duplicates when every compared value is equal. A few edge cases follow from how pandas compares values.
Missing values match each other
In ordinary Python and NumPy arithmetic, NaN == NaN is False. The duplicate logic treats missing values as equal to each other, so two rows with NaN in the same place can be duplicates:
import pandas as pd
df = pd.DataFrame({
"a": [1, 1, None, None],
"b": ["x", "x", "y", "y"],
})
print(df.drop_duplicates().index.tolist()) # [0, 2]Rows 2 and 3 both have NaN in column a and "y" in column b, so row 3 is dropped. If you expected missing values to count as unknown and different, handle them before deduplicating, for example by filling them with a distinct marker or by splitting the table.
Types matter
Numeric values compare by value, so 1 and 1.0 are equal. A string and a number are never equal, so "1" and 1 are different:
import pandas as pd
nums = pd.DataFrame({"v": [1, 1.0]})
print(len(nums.drop_duplicates())) # 1
mixed = pd.DataFrame({"v": ["1", 1]})
print(len(mixed.drop_duplicates())) # 2Check df.dtypes before deduplicating a column that came from a CSV file or an Excel sheet. Mixed types often explain why duplicates "survive".
Text must match exactly
Comparison is exact and case-sensitive. Extra spaces count as a difference:
import pandas as pd
df = pd.DataFrame({"customer": ["Bob", "bob", "Bob "]})
print(len(df.drop_duplicates())) # 3Visually identical rows can be distinct. If you see apparent duplicates in the output, look for trailing whitespace, different capitalization, or non-breaking spaces. A later chapter covers normalizing values before deduplicating.
Floating-point values
Floats compare by exact binary value. The sum 0.1 + 0.2 is 0.30000000000000004, which is not equal to 0.3, so those two rows are not duplicates. When values come from calculations, round them first with df["total"].round(2).
Unhashable values
Cells that hold lists, dictionaries, or sets cannot be hashed. The method has to hash each row to find repeats, so it raises TypeError: unhashable type: 'list'. Convert such a column to something hashable, such as a tuple or a string, or leave it out with subset.
Comparing columns: a quick preview of subset
By default every column takes part. Often you care about only a key, such as order_id, and want to ignore columns that may differ between copies, such as a timestamp. The subset argument handles this:
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 2],
"loaded_at": ["09:00", "09:01", "09:05"],
})
print(len(df.drop_duplicates())) # 3
print(len(df.drop_duplicates(subset="order_id"))) # 2With all columns compared, nothing is dropped, because loaded_at differs. With subset="order_id", the second row for order 2 is removed. The next chapter covers choosing which row survives.
Resetting the index
When rows are removed, the original labels stay. After drop_duplicates() the index may have gaps, as in the first example. Pass ignore_index=True to renumber the result:
import pandas as pd
df = pd.DataFrame({"a": [1, 1, 2]})
print(df.drop_duplicates().index.tolist()) # [0, 2]
print(df.drop_duplicates(ignore_index=True).index.tolist()) # [0, 1]Use ignore_index=True only when the old labels carry no meaning. If the index holds something useful, such as a row number from the source file or a timestamp, keep it. It tells you which original rows survived.
Inspect before you delete
Removing data is hard to undo, so look at what you are about to drop. Use duplicated() as a preview, and use keep=False to see every member of each duplicate group:
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().sum()) # 1 row would be dropped
print(df[df.duplicated(keep=False)]) # both copies of order 2Showing both copies lets you confirm they really are the same record and not two legitimate orders that happen to match. After the cleanup, check the row count, and check that the dropped count matches your preview:
before = len(df)
clean = df.drop_duplicates()
after = len(clean)
print(before - after == df.duplicated().sum()) # TrueA final sanity check is that no duplicates remain: assert not clean.duplicated().any().
Common errors
- No change after calling the method. The result was not assigned. Write
df = df.drop_duplicates(). dfisNone. You assigned the result ofinplace=True. Drop the assignment or dropinplace.- Duplicates remain. The values differ in case, spacing, dtype, or float precision. Inspect with
df[col].unique()ordf[col].map(repr)to see hidden differences. - Too many rows removed. Missing values matched each other, or you used
subsetwith columns that are not a true key. TypeError: unhashable type. A column holds lists or dictionaries. Convert it or exclude it.- Gaps in the index. This is expected. Use
ignore_index=Trueorreset_index(drop=True).
Exercise
A DataFrame has columns "email" and "signupdate". The rows (0, "[email protected]", "2026-01-01"), (1, "[email protected]", "2026-01-01"), and (2, "[email protected]", "2026-01-01") are present, plus one row (3, None, "2026-02-01") and another (4, None, "2026-02-01"). How many rows does df.dropduplicates() return, which index labels survive, and why is the row with "[email protected]" still there?
Show answer
It returns 3 rows, with index labels 0, 2, and 3. Row 1 is dropped because it matches row 0 in every column. Row 4 is dropped because missing values in the same position are treated as equal, so it matches row 3. Row 2 survives because "[email protected]" and "[email protected]" differ in case, and comparison is exact. To merge them, lowercase the column first, for example with df["email"].str.lower().
Exercise
You run df.drop_duplicates() on a DataFrame with 1,000 rows and the length of df is still 1,000 afterward. List two possible causes and say how you would check each.
Show answer
First, the result was not assigned, so the original df is unchanged. Check by assigning the result to a new variable and comparing lengths. Second, the rows are not exact duplicates because of differences in case, whitespace, dtype, or floating-point precision, or because a column such as a timestamp differs. Check with df.duplicated().sum(), and try df.duplicated(subset=[the key columns]).sum() to see whether duplicates appear once the extra columns are ignored.