Overview
Two rows are duplicates when the columns you care about hold equal values. The hard part is the word equal. To a person, Ann Lee and ann lee are one customer, and 1.0 and 1 are one number, but a naive comparison treats them as different. This template first rewrites each cell into a standard form, then joins the compared cells of a row into one key. Rows with the same key fall into the same group, and one pass over the table is enough to find every group.
A short history
Removing repeated records is a working practice of data management with no single inventor. Its formal side is record linkage: Howard Newcombe and colleagues described automatic matching of health records in 1959, and Ivan Fellegi and Alan Sunter gave the statistical theory in 1969. Exact duplicate removal by key became routine with relational databases and with extract, transform, load work for data warehouses.
How it works
- Choose the columns to compare with subset. Leaving it empty compares every column.
- Normalise each compared cell: a missing value (None or NaN) becomes one shared marker, numbers become floats, and text is optionally trimmed and lower-cased.
- If numeric_tolerance is positive, replace each number by the index of the bucket it falls in, so nearby numbers get the same value.
- Join the normalised cells of a row into a tuple. This tuple is the row's key.
- Walk the rows once and collect the row positions under each key in a dictionary. A key with two or more positions is a duplicate group.
- Apply keep: first keeps the earliest row of each group, last keeps the latest, none drops the whole group. The surviving rows stay in their original order.
Watch out for
- Tolerance works by buckets, not by distance. With a tolerance of 0.1 the values 1.04 and 1.06 land in different buckets although they differ by only 0.02, so some near-duplicates are missed.
- Comparing too few columns merges rows that are truly different. Two customers who share a name are not one customer, so include enough columns in subset to identify a record.
- Removing duplicates after the train and test split leaves copies on both sides, and the test score then rewards memorising. Deduplicate first.
- Two missing cells compare as equal here, so rows that differ only in what is unknown are merged. That is a choice, and it may be wrong for your data.
Use cases
When to use it
Before splitting or training on any table built from merges, repeated exports or manual entry. Repeated rows give some examples extra weight and can put the same example in both the training and the test set.
In industry
- Customer data
- Companies merge customer records entered more than once with small differences in name or address, so each person is counted and contacted once.
- Official statistics
- Census and health agencies link and deduplicate records across sources so that a person or event is not counted twice.
- Machine learning
- Teams drop repeated rows before splitting, so that the same example cannot sit in both the training and the test set.
Choosing it: what must hold
- A clear rule for what counts as the same record: which columns to compare and how strictly.
- Values normalised first, for example trimmed text and consistent case, or the same record will look different.
- A decision on which copy to keep: the first, the last, or none.
- Confidence that repeated rows are errors. Repeated rows can be real, such as two identical purchases.
When to choose something else
| If | Use instead |
|---|---|
| Records differ by typos or word order, not only by case and spacing | Fuzzy matching or record linkage with string similarity |
| The differences come from mixed formats such as date or phone styles | Standardising inconsistent formats first, then deduplicating |
| Repeated rows are real events that matter for the count | Keep them, and add an id or timestamp column to tell them apart |
Math foundations
The comparison key
Row is reduced to the normalised values of the compared columns. Two rows are duplicates exactly when their keys are equal.
Numeric buckets
With a tolerance , a number is replaced by the index of the nearest multiple of . Numbers with the same index count as equal.
How many rows are unique
Each duplicate group contributes one distinct row and surplus copies. Subtracting the surplus from the row count gives the number of distinct rows.
Cost
Building a key reads cells, and a dictionary lookup takes constant time on average. Comparing every pair of rows would instead cost on the order of .
Symbols
- one row of the table
- the indices of the compared columns (subset)
- the normalisation applied to one cell
- the comparison key of row r
- numeric_tolerance, the bucket width
- the set of duplicate groups
- the number of rows in group g
- the number of rows and the number of distinct rows
Worked by hand
A table has rows. Rows 0, 2 and 5 share one key and rows 1 and 4 share another. Row 3 is alone. Separately, test the tolerance on the values 0.96, 1.04 and 1.06.
Three distinct rows remain. With keep set to first the survivors are rows 0, 1 and 3. The values 0.96 and 1.04 match although they are 0.08 apart, while 1.04 and 1.06 do not match although they are only 0.02 apart.
Visual example
Loading the example.
Try this
- Turn on ignore_case and strip_whitespace: rows 0 and 1 get the same key and become one group.
- With ignore_case still on, raise the tolerance to 0.05, then to 0.1. Rows 5 and 6 merge at 0.05 and split again at 0.1, because 7.04 and 7.06 fall on two sides of a bucket edge.
- Compare only the name column and see which different purchases get merged.
Code sample
from impl import Deduplicator
from config import DeduplicatorConfig
rows = [("Ann", "[email protected]", 31), ("Bob", "[email protected]", 45), ("ann ", "[email protected]", 31)]
dedup = Deduplicator(DeduplicatorConfig(subset=(1,), ignore_case=True))
kept, kept_indices = dedup.drop(rows) # the third row repeats the first row's email
print(kept_indices) # [0 1]Read the implementation (104 lines)
"""Duplicate detection and removal for tables of mixed values (numbers, text, missing).
Standard library and NumPy only. Each row is turned into a hashable key built from the compared columns, after
optional normalisation (case, whitespace, numeric rounding). Rows with equal keys are duplicates. One pass
over the rows, so the cost is linear in the number of rows.
"""
from __future__ import annotations
import math
import numbers
import numpy as np
try:
from .config import DeduplicatorConfig
except ImportError: # run from the template's own folder
from config import DeduplicatorConfig
_MISSING = ("<missing>",) # one shared key for None and NaN, so two missing cells compare as equal
class Deduplicator:
"""Finds and drops duplicate rows. Rows are any sequence of sequences or a 2-D array (n_rows, n_columns)."""
def __init__(self, config: DeduplicatorConfig | None = None) -> None:
self.config = config or DeduplicatorConfig()
def _normalise(self, value):
"""Turn one cell into the hashable value it is compared by."""
if isinstance(value, np.generic):
value = value.item()
if value is None:
return _MISSING
if isinstance(value, bool):
return ("bool", value) # tagged, because Python treats True == 1 and would merge them
if isinstance(value, numbers.Real):
if isinstance(value, float) and math.isnan(value):
return _MISSING
tol = self.config.numeric_tolerance
if tol > 0:
return int(round(float(value) / tol))
return float(value) # 1 and 1.0 are the same number
if isinstance(value, str):
if self.config.strip_whitespace:
value = " ".join(value.split())
if self.config.ignore_case:
value = value.casefold()
return value
return value if isinstance(value, (tuple, bytes, frozenset)) else repr(value)
def keys(self, rows) -> list[tuple]:
"""One comparison key per row."""
subset = self.config.subset
out = []
for row in rows:
row = list(row) if not isinstance(row, (str, bytes)) and hasattr(row, "__iter__") else [row]
if subset is not None:
if max(subset) >= len(row):
raise ValueError(f"subset {subset} does not fit a row with {len(row)} columns")
row = [row[c] for c in subset]
out.append(tuple(self._normalise(v) for v in row))
return out
def groups(self, rows) -> list[list[int]]:
"""Groups of row indices that are duplicates of each other (only groups with two or more rows)."""
seen: dict[tuple, list[int]] = {}
for i, key in enumerate(self.keys(rows)):
seen.setdefault(key, []).append(i)
return [g for g in seen.values() if len(g) > 1]
def duplicate_mask(self, rows) -> np.ndarray:
"""Boolean array (n_rows,): True for the rows that `drop` removes under the configured `keep`."""
n = len(rows)
mask = np.zeros(n, dtype=bool)
for group in self.groups(rows):
if self.config.keep == "first":
mask[group[1:]] = True
elif self.config.keep == "last":
mask[group[:-1]] = True
else:
mask[group] = True
return mask
def drop(self, rows):
"""Remove duplicates. Returns (kept_rows, kept_indices).
kept_rows has the type of the input: an array for an array, a list otherwise. Original order is kept.
kept_indices: integer array of the surviving row positions.
"""
kept = np.flatnonzero(~self.duplicate_mask(rows))
if isinstance(rows, np.ndarray):
return rows[kept], kept
return [rows[i] for i in kept], kept
def summary(self, rows) -> dict:
"""Counts: {"rows", "duplicate_groups", "rows_to_drop", "unique_rows"}."""
groups = self.groups(rows)
n = len(rows)
return {
"rows": n,
"duplicate_groups": len(groups),
"rows_to_drop": int(self.duplicate_mask(rows).sum()),
"unique_rows": n - sum(len(g) - 1 for g in groups),
}- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Build a list of eight rows of (name, city, amount) in which some names differ only in case or spacing and some amounts differ by a cent. Run Deduplicator.summary and Deduplicator.groups with the default DeduplicatorConfig, then again with ignore_case, strip_whitespace and numeric_tolerance set. Explain each change in the counts, then call drop with keep set to none and check the kept indices.
Check on learning
- The same customer appears twice with different purchase amounts. Should the two rows be treated as duplicates? What does your answer depend on?
A way to think about it
Ask what one row is meant to represent: a customer or a purchase. Then decide which columns belong in subset for that meaning.
- Why does a rounding bucket fail to merge some values that are closer together than the tolerance, and what would a rule based on true distance cost instead?
A way to think about it
Place two values on either side of a bucket edge. Then think about how many pairs you would have to compare if equality could no longer be read from a key.
- A model scores 99 percent on its test set. After deduplicating the full table and splitting again it scores 91 percent. What most likely happened?
A way to think about it
Think about where the copies of one row could have ended up in the first split, and what the model had already seen.
- When would keep set to none be a better choice than keeping the first row of each group?
A way to think about it
Consider groups whose rows agree on the compared columns but disagree on the label. Which copy would you trust?