research/deduplicating-customers-from-two-csv-exports
Deduplicating Customer Records From Two CSV Exports: Matching on Email and Phone, and Where It Merges the Wrong People
Engineering Note · December 2, 2026 · 9 minute read · Python · CSV · Data · Customers
Matching two customer exports on a cleaned-up email address and phone number finds most real duplicates, and it also merges people who are not the same. We ran a small, deliberately awkward pair of CSV files through three versions of a Python script. Matching on email alone missed duplicates. Adding phone and chaining the matches together found more, and merged a couple, two co-workers and two strangers who both typed 000-000-0000. The version that worked looked at one pair at a time, threw away placeholder phones, stripped invisible characters from emails, and only merged automatically when the names agreed. Everything else went to a list for a person to decide.
Everything below was run on Linux with Python 3.11.18 and only its standard library (csv, re, unicodedata, collections). The outputs are the real ones from these runs. This note goes with today’s article, Your Customer List Is an Asset.
What were the two exports?
We wrote two small files by hand, shaped like a booking tool’s customer export and an invoicing tool’s: an ID, a name, an email and a phone. Each row was chosen to test one thing. All names, addresses and numbers are made up.
booking.csv:
id,name,email,phone
B1,Ann Lee,ann.lee@example.com,(502) 555-0142
B2,Tom Baker,TBaker@Example.com ,502-555-0199
B3,Cara Diaz,cara@example.net,
B4,Dan Ortiz,dan@example.org,+1 502 555 0110
B5,Eve Park,eve.park@gmail.com,5025550175
B6,Sam Hill,info@hillfamily.example,502.555.0123
B7,Pat Hill,info@hillfamily.example,502.555.0124
B8,Jo Kim,jo.kim@example.com,502-555-0150 ext. 12
B9,Lou Grant,front@grantplumbing.example,502-555-0188
B10,Kara Mendez,kara@example.com,502-555-0161
invoices.csv:
id,name,email,phone
I1,Ann Lee,ann.lee@example.com,502-555-0142
I2,Thomas Baker,tbaker@example.com,
I3,Cara Diaz,cara.diaz@work.example,(502) 555-0101
I4,Daniel Ortiz,,5025550110
I5,Eve Park,evepark@gmail.com,
I6,Sam Hill,sam@hillroofing.example,502-555-0123
I7,Jo Kim,jo.kim@example.com,502-555-0150
I8,Maria Grant,mgrant@example.com,502-555-0188
I9,Ray Cole,ray@example.com,000-000-0000
I10,Kim Wu,kim@example.com,000-000-0000
I11,Kara Mendez,kara@example.com,
Two things are not visible here. B2’s email has a trailing space. I11’s email ends with a zero-width space (U+200B), the kind of invisible character that comes along when an address is copied from a web page or a chat. od -c shows it as three extra bytes:
0000100 m p l e . c o m 342 200 213 , \n
What we intended, as the person who knows these customers: Ann, Tom/Thomas, Dan/Daniel, Jo and Kara are each one person in both files. Sam Hill in B6 and I6 is one person, with a family email and a business email. Pat Hill is Sam’s spouse, sharing the family email. Lou and Maria Grant work at the same plumbing business and share its line. Ray Cole and Kim Wu are strangers who both typed a placeholder phone. Cara and Eve are the same people in both files, with different details.
Version 1: what does matching on email alone find?
The first script lowercases and trims emails, strips everything but digits from phones (dropping a leading 1 from 11-digit numbers), and groups any rows that share a key using a union-find, a standard structure that keeps merging groups as matches come in.
def norm_email(e):
return (e or "").strip().lower() or None
def norm_phone(p):
d = re.sub(r"\D", "", p or "")
if len(d) == 11 and d.startswith("1"):
d = d[1:]
return d or None
Matching on email alone:
email: 21 rows -> 17 customers, 4 merged groups
B1 Ann Lee + I1 Ann Lee
B2 Tom Baker + I2 Thomas Baker
B6 Sam Hill + B7 Pat Hill
B8 Jo Kim + I7 Jo Kim
Trimming and lowercasing joined Tom and Thomas. It missed Dan (no email in the invoice), and it missed Kara, because str.strip() does not remove a zero-width space. It merged Sam and Pat Hill on their shared family email, which is wrong.
Version 1 with phone: what goes wrong when matches chain?
Adding the phone as a second key:
email+phone: 21 rows -> 13 customers, 7 merged groups
B1 Ann Lee + I1 Ann Lee
B2 Tom Baker + I2 Thomas Baker
B4 Dan Ortiz + I4 Daniel Ortiz
B6 Sam Hill + B7 Pat Hill + I6 Sam Hill
B8 Jo Kim + I7 Jo Kim
B9 Lou Grant + I8 Maria Grant
I9 Ray Cole + I10 Kim Wu
Dan was found. Three new mistakes appeared:
- A chain. Pat Hill shares an email with
B6, andB6shares a phone withI6, so the union-find put all three in one customer. Pat andI6have nothing in common. - A shared business line. Lou and Maria Grant became one person.
- A placeholder. Ray Cole and Kim Wu became one person because both typed
000-000-0000.
Jo Kim’s phone with ext. 12 also became 502555015012, twelve digits that matched nothing. The email caught Jo anyway, but a phone-only match would have been missed.
Did strip() really leave the zero-width space?
Yes. A direct check of Python’s str.strip() on four kinds of padding:
'a@b.com\xa0' -> 'a@b.com'
'a@b.com\u200b' -> 'a@b.com\u200b'
'\ufeffa@b.com' -> '\ufeffa@b.com'
' a@b.com\t' -> 'a@b.com'
strip() removes whitespace, including the non-breaking space (\xa0). The zero-width space and the byte-order mark (\ufeff) are not whitespace to Python, so they stay. Two addresses that look identical on screen compare as different.
Version 2: how do pairwise decisions and name checks fix it?
The final script changes four things:
- Cleaner keys. Emails go through Unicode NFKC normalization (which, among other things, turns full-width characters into ordinary ones), have zero-width characters and the byte-order mark removed, then are trimmed and lowercased. Phones lose a trailing extension before the digits are taken, and anything that is not exactly ten digits, or is one digit repeated, is ignored.
- Pairs, not chains. Every pair of rows that shares a cleaned key becomes a candidate, with the reason recorded. Nothing is grouped yet.
- A name check per pair. A pair is merged automatically only if the last names match and one first name starts with the other, which allows Dan/Daniel.
- A review list. Every other candidate pair goes to a person.
import csv, re, unicodedata
from collections import defaultdict
INVISIBLE = dict.fromkeys(map(ord, "\u200b\u200c\u200d\u2060\ufeff"))
def norm_email(e):
e = unicodedata.normalize("NFKC", e or "").translate(INVISIBLE).strip().lower()
return e if "@" in e else None
def norm_phone(p):
p = re.split(r"(?i)\s*(?:ext\.?|x)\s*\d+\s*$", p or "")[0]
d = re.sub(r"\D", "", p)
if len(d) == 11 and d.startswith("1"):
d = d[1:]
if len(d) != 10 or len(set(d)) == 1:
return None # wrong length or a placeholder like 000-000-0000
return d
def load(path):
with open(path, newline="", encoding="utf-8-sig") as f:
return list(csv.DictReader(f))
rows = load("booking.csv") + load("invoices.csv")
by_key = defaultdict(list)
for r in rows:
if (e := norm_email(r["email"])): by_key[("email", e)].append(r)
if (p := norm_phone(r["phone"])): by_key[("phone", p)].append(r)
def names_agree(a, b):
fa, fb = a.strip().lower().split(), b.strip().lower().split()
if fa[-1] != fb[-1]: return False # last names must match
x, y = fa[0], fb[0]
return x.startswith(y) or y.startswith(x) # Dan/Daniel
pairs = defaultdict(set)
for (kind, val), rs in by_key.items():
for i in range(len(rs)):
for j in range(i + 1, len(rs)):
pairs[(rs[i]["id"], rs[j]["id"])].add(f"{kind} {val}")
byid = {r["id"]: r for r in rows}
auto, review = [], []
for (a, b), why in pairs.items():
ok = names_agree(byid[a]["name"], byid[b]["name"])
line = f'{a} {byid[a]["name"]} + {b} {byid[b]["name"]} ({", ".join(sorted(why))})'
(auto if ok else review).append(line)
print(f"{len(rows)} rows, {len(pairs)} candidate pairs")
print("merge automatically:"); [print(" " + a) for a in auto]
print("send to a person:"); [print(" " + a) for a in review]
The output, plus a last check that lists people with the same name who shared no email or phone:
21 rows, 8 candidate pairs
merge automatically:
B1 Ann Lee + I1 Ann Lee (email ann.lee@example.com, phone 5025550142)
B4 Dan Ortiz + I4 Daniel Ortiz (phone 5025550110)
B6 Sam Hill + I6 Sam Hill (phone 5025550123)
B8 Jo Kim + I7 Jo Kim (email jo.kim@example.com, phone 5025550150)
B10 Kara Mendez + I11 Kara Mendez (email kara@example.com)
send to a person:
B2 Tom Baker + I2 Thomas Baker (email tbaker@example.com)
B6 Sam Hill + B7 Pat Hill (email info@hillfamily.example)
B9 Lou Grant + I8 Maria Grant (phone 5025550188)
same name, no shared email or phone:
B3 <cara@example.net> - + I3 <cara.diaz@work.example> (502) 555-0101
B5 <eve.park@gmail.com> 5025550175 + I5 <evepark@gmail.com> -
The placeholder pair is gone, because 000-000-0000 is no longer a key. Kara now matches. Jo matches on the phone as well as the email, because the extension was removed first. The Hills and the Grants go to a person instead of being merged.
Two things the rules still did not get right:
- Tom and Thomas went to review. “thomas” does not start with “tom”, so the prefix rule fails. That is the safe direction to be wrong in. A nickname table would fix it and add its own mistakes.
- Cara and Eve were never candidates. Cara used a different email and only one file has her phone. Eve’s two addresses differ only by a dot. Whether a mailbox provider treats those as the same address is the provider’s rule, not something a script can assume, so we did not fold dots. The same-name report is the only place these show up, and it is a list for a person, not a match.
Does it hold up at a realistic size?
We generated two 25,000-row files with random first and last names from small lists, unique emails and unique phones, and copied 1,250 booking rows into the invoice file as planted duplicates.
50000 rows, 1252 candidate pairs
The script took about 0.5 seconds. It merged 1,251 pairs automatically: the 1,250 planted ones, plus one pair our generator created by accident when two random rows got the same name and the same index, and therefore the same email. It sent one pair to review, another generator accident where two different names produced the same email string. The same-name report listed 11,696 groups, which is why a name alone is useless as a matching key: with 15 first names and 4,000 last names, thousands of different people share a name.
Our first attempt drew phones from only 10,000 numbers, so many unrelated rows shared one. That produced 126,221 candidate pairs, almost all for review, and took about a second. Pairwise matching grows with the square of the number of rows that share a key. A key shared by hundreds of rows is not identifying anyone, so in real data, count how many rows share each phone and email and set the busy ones aside before pairing.
What should a small business take from this?
- Clean emails with NFKC, remove invisible characters, then trim and lowercase.
strip()alone is not enough. - Remove extensions before taking phone digits, and drop placeholders instead of matching on them.
- Decide pair by pair, merge automatically only when the names agree, and send the rest to a person.
- Keep the original exports, and run the merge as a dry run first.
Limitations
- The test files were written by hand to cover specific cases. We did not export from real booking or invoicing tools, whose files may use different columns, encodings and formats.
- The phone rules assume US and Canada style ten-digit numbers. International numbers are ignored by
norm_phone, so they never match. Today’s other note, Normalizing Phone Numbers Typed Into a Form Without a Library, looks at those rules in detail. - The name rule only checks the first and last words of a name. Hyphenated names, name changes, reversed name order and nicknames are not handled.
- Lowercasing the whole email address is a choice. We did not check any mail provider’s rules for case or dots.
- The large test used synthetic data with uniform random names. Real customer lists have more common names and more shared contact details, so expect a longer review list.
Related reading
- Your Customer List Is an Asset: Where It Lives, Who Can Export It, and How to Keep One Clean Copy
- Parsing a Spreadsheet’s CSV Export: Quoted Commas, a Byte-Order Mark and Excel Date Serials
- A Dry-Run Mode for a Script That Changes Data: Printing the Plan Before Applying It
Frequently asked questions
What is the safest way to match duplicate customers across two lists?
Clean the email and phone first, then treat a shared email or phone as a reason to look at a pair, not as proof. Merge automatically only when the names also agree, and send every other pair to a person who knows the customers. Keep the original exports so a wrong merge can be undone.
Why did matching on phone number merge different people?
Families, couples and small businesses share phone numbers, and people type placeholders like 000-000-0000 when a form insists on a phone. In our test a shared office line matched Lou Grant with Maria Grant, and a placeholder matched two strangers. A phone match needs the name to agree before it is trusted.
Why is chaining duplicate matches dangerous?
If A matches B on email and B matches C on phone, a chaining approach puts A, B and C in one group even when A and C have nothing in common. In our test this put Pat Hill, who shared a family email with Sam Hill, into the same customer as Sam Hill's business record. Decide pair by pair, and only group pairs you have accepted.
Does lowercasing and trimming an email address catch every duplicate?
No. In our test, Python's str.strip() removed spaces, tabs and a non-breaking space, but not a zero-width space or a byte-order mark, so a copied address with an invisible character did not match. We added Unicode NFKC normalization and removed those characters explicitly.
How fast is pairwise matching on a few thousand customers?
Fast enough not to matter for a small business. Our script handled 50,000 synthetic rows in about half a second with Python 3.11, because it only compares records that already share a cleaned email or phone. It slows down when one value, such as a placeholder phone, is shared by thousands of rows, so filter those first.