How to Find and Handle Duplicate Rows in a Dataset
How do you find and remove duplicate rows in a dataset?
First decide what counts as a duplicate: an exact copy of every column, or two rows with the same business key (such as customer_id) but different values. Count both kinds, inspect examples, define a rule for which record to keep (for example, the most recently updated), apply it with ROW_NUMBER() in SQL or drop_duplicates() in pandas, and reconcile row counts before and after.
Exact duplicates vs. duplicate keys
Exact duplicates are usually load errors — the same file imported twice. Duplicate keys are harder: two customer rows with the same ID but different addresses may mean one is outdated, or that the key isn't really unique. These need a business rule, not a blanket delete.
Find duplicates in SQL
-- Duplicate business keys and how many copies each has
SELECT customer_id, COUNT(*) AS copies
FROM customers
GROUP BY customer_id
HAVING COUNT(*) > 1
ORDER BY copies DESC;To keep one row per key, rank rows within each key and keep rank 1. Filter the ranked result in an outer query or CTE:
WITH ranked AS (
SELECT c.*,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY updated_at DESC, load_id DESC
) AS rn
FROM customers c
)
SELECT *
FROM ranked
WHERE rn = 1;Add a tie-breaker (load_id above) so the result is deterministic when two rows share the same updated_at.
Find duplicates in pandas
import pandas as pd
exact_dupes = df.duplicated(keep=False).sum()
key_dupes = df.duplicated(subset=["customer_id"], keep=False).sum()
print(f"exact: {exact_dupes}, by key: {key_dupes}")
# Inspect before deciding
df[df.duplicated(subset=["customer_id"], keep=False)].sort_values("customer_id")
# Keep the latest record per customer
deduped = (df.sort_values(["customer_id", "updated_at"])
.drop_duplicates(subset=["customer_id"], keep="last"))
print(len(df), "->", len(deduped))Validate the result
- Confirm the key is now unique.
- Record how many rows were removed and why.
- Reconcile totals (revenue, quantity) to check you didn't drop real activity.
- Keep the removed rows in a separate table or file so the change is reversible.
Related skills
Data Analyst Toolkit includes AI-agent skills that follow this method: