Data analysis · Intermediate · 16 min
Match misspelt names and places with fuzzy matching
By Padding · Updated 18 Nov 2026
Python 3.15.2 · pandas 3.1.1 · RapidFuzz 3.14.6 · uv 0.13 (checked on python:3.15-slim)
You will clean a column of hand-typed town names with RapidFuzz and pandas, auto-accept the strong matches, send the doubtful ones to a review file and save the approved mapping so the next batch matches exactly.
On this page
Field data spells places in more ways than you would think possible. A survey run across south-west Nigeria comes back with Ibadan, IBADAN, ibadan, Ibadn and Ibadan North in the same column, plus Ogbomoso next to the official Ogbomosho, and Oshogbo next to Osogbo. A groupby on that column gives you five Ibadans, and a join to a list of towns drops most of them.
Fixed rules (strip, upper, a hand-written replace list) handle the case and spacing problems; clean a CSV file with pandas covers those. They cannot guess that Abekuta is Abeokuta. Fuzzy matching can: it scores how similar two strings are, so each messy name can be paired with the closest entry in a reference list.
The catch is that a fuzzy matcher always has an answer, and some answers are confidently wrong. In this tutorial you build a small pipeline with RapidFuzz and pandas that normalises the text, compares three scorers, matches every name against a reference list, accepts only the strong matches, sends the rest to a person in a review file, and saves the decisions as a mapping. The next batch of data then matches exactly from the mapping, and only names nobody has seen before go back for review.
Step 1 · Set up the project and the two files
Make a throwaway folder, start a uv project and add pandas and RapidFuzz, pinned so your scores match the ones below:
mkdir -p ~/fuzzy-demo
cd ~/fuzzy-demo
uv init --no-package --python 3.15
uv add "pandas==3.1.1" "rapidfuzz==3.14.6"Now write the data. towns.csv is the reference list: the spellings you want in your analysis, one row per town. responses.csv is what came back from the field, one row per survey response, with the town as each enumerator typed it. Row 7 uses Yoruba tone marks, row 3 starts with a space, and row 25 is a town that is not in the study area at all.
cd ~/fuzzy-demo
cat > towns.csv <<'CSV'
town,state
Ibadan,Oyo
Ogbomosho,Oyo
Oyo,Oyo
Iseyin,Oyo
Saki,Oyo
Abeokuta,Ogun
Ijebu-Ode,Ogun
Osogbo,Osun
Ile-Ife,Osun
Iwo,Osun
Ilorin,Kwara
CSV
cat > responses.csv <<'CSV'
response_id,town
1,Ibadan
2,IBADAN
3, ibadan
4,Ibadn
5,Ibadan North
6,Ogbomoso
7,Ògbómọ̀ṣọ́
8,Abeokuta
9,Abekuta
10,Ilorin
11,Illorin
12,"Ilorin, Kwara"
13,Oyo Town
14,Osogbo
15,Oshogbo
16,Ile-Ife
17,Ile Ife
18,Ife
19,Iseyin
20,Iseyn
21,Shaki
22,Ijebu Ode
23,Ode Ijebu
24,Iwo Road
25,Lagos
26,Ibadan
27,Ogbomoso
28,Ibadn
CSV
wc -l towns.csv responses.csvCheck it worked
wc -l reports 12 lines for towns.csv (a header and 11 towns) and 29 for responses.csv (a header and 28 responses). uv run python -c "import rapidfuzz; print(rapidfuzz.__version__)" prints 3.14.6.
Step 2 · Normalise case, accents and spacing first
Before any fuzzy scoring, remove the differences that are not spelling mistakes. Put the rule in its own module so every later script uses the same one:
cd ~/fuzzy-demo
cat > clean.py <<'PY'
import re
import unicodedata
def normalise(name: str) -> str:
"""Lower-case, drop accents and punctuation, collapse spaces."""
decomposed = unicodedata.normalize("NFKD", name)
no_accents = "".join(c for c in decomposed if not unicodedata.combining(c))
words = re.sub(r"[^\w\s]", " ", no_accents.casefold())
return " ".join(words.split())
PY
cat > normalise_check.py <<'PY'
import pandas as pd
from clean import normalise
responses = pd.read_csv("responses.csv")
responses["town_norm"] = responses["town"].map(normalise)
print("rows:", len(responses))
print("distinct as typed:", responses["town"].nunique())
print("distinct after normalising:", responses["town_norm"].nunique())
print(responses[["town", "town_norm"]].drop_duplicates().head(8).to_string(index=False))
PY
uv run normalise_check.pyEach line of normalise does one job:
NFKDsplits a letter such asọ̀into a plainofollowed by separate combining marks (the dot below and the tone mark), and the next line drops the marks. Yoruba, Hausa, French and Portuguese place names all arrive with and without them, depending on the keyboard the enumerator had.casefold()is a strongerlower()meant for comparing text.- The
re.subturns hyphens and commas into spaces, soIle-IfeandIle Ifebecome the same string. " ".join(words.split())trims both ends and collapses runs of spaces.
Keep the original column. You want to see what was typed when you review matches later, and you never want to lose it.
Check it worked
The script prints rows: 28, distinct as typed: 25 and distinct after normalising: 21. In the table, Ibadan, IBADAN and ibadan all show ibadan, and both Ogbomoso and Ògbómọ̀ṣọ́ show ogbomoso. Four variants are gone without any guessing. ibadn is still separate, because that one is a real typo.
Step 3 · Compare three scorers on pairs you can judge
RapidFuzz gives a score from 0 to 100 for a pair of strings. Which scorer you pick changes what counts as similar, so try three of them on pairs where you already know the right answer:
cd ~/fuzzy-demo
cat > scorers.py <<'PY'
from rapidfuzz import fuzz
pairs = [
("ibadn", "ibadan"),
("ode ijebu", "ijebu ode"),
("ibadan north", "ibadan"),
("iwo road", "iwo"),
("lagos", "ogbomosho"),
]
print(f"{'typed':<14}{'reference':<12}{'ratio':>7}{'token_sort':>12}{'WRatio':>8}")
for typed, ref in pairs:
print(f"{typed:<14}{ref:<12}"
f"{fuzz.ratio(typed, ref):>7.1f}"
f"{fuzz.token_sort_ratio(typed, ref):>12.1f}"
f"{fuzz.WRatio(typed, ref):>8.1f}")
PY
uv run scorers.pyWhat the numbers tell you:
ratiocompares the two strings character by character. One missing letter in a six-letter word (ibadn) still scores 90.9, but swapped words (ode ijebu) fall to 55.6.token_sort_ratiosorts the words before comparing, so word order stops mattering andode ijebuscores 100. It does nothing for extra words.WRatiocombines several methods. When one string is much longer than the other, it also looks for the short one inside the long one and scales that partial match down a little, which is whyibadan northandiwo roadboth score exactly 90.
That last row is the warning. Iwo Road is a busy district of Ibadan, not the town of Iwo, and WRatio scores it as highly as the genuine ibadan north. No scorer knows local geography. WRatio is a sensible default for messy names, because it handles typos, word order and extra words, but a score of 90 means "worth a look", not "correct".
Check it worked
You see five rows. ode ijebu scores 55.6, 100.0 and 95.0 across the three columns, iwo road scores 90.0 under WRatio, and lagos against ogbomosho stays at 42.9 for every scorer.
Step 4 · Match every name to the reference list with extractOne
process.extractOne scores one query against a whole list of choices and returns the best. Pass the choices as a dictionary of {display name: normalised name}: RapidFuzz compares against the values and hands back the key, so you get Ijebu-Ode with its hyphen, not the normalised form. score_cutoff=80 makes it return None when nothing scores at least 80, rather than offering a poor best guess.
Match the 21 distinct normalised names, not the 28 rows. On a real file with 100,000 rows and a few hundred spellings, that is the difference between seconds and minutes.
cd ~/fuzzy-demo
cat > match.py <<'PY'
import pandas as pd
from rapidfuzz import fuzz, process
from clean import normalise
towns = pd.read_csv("towns.csv")
choices = {town: normalise(town) for town in towns["town"]}
responses = pd.read_csv("responses.csv")
names = sorted(responses["town"].map(normalise).unique())
rows = []
for name in names:
best = process.extractOne(name, choices, scorer=fuzz.WRatio, score_cutoff=80)
if best is None:
rows.append({"town_norm": name, "suggested": None, "score": None})
else:
_, score, town = best
rows.append({"town_norm": name, "suggested": town, "score": round(score, 1)})
matches = pd.DataFrame(rows)
matches.to_csv("matches.csv", index=False)
print(matches.to_string(index=False))
PY
uv run match.pyThe tuple from extractOne is (matched value, score, key). With a list of choices instead of a dictionary, the third item is the position in the list.
RapidFuzz does not lower-case or strip anything unless you ask it to: the processor argument defaults to None. That is why you normalised first. You could pass processor=utils.default_process, but it does not remove accents, and keeping your own normalise means the review file shows exactly the strings that were compared.
Check it worked
The table has 21 rows. abekuta maps to Abeokuta at 93.3, ode ijebu to Ijebu-Ode at 95.0, shaki to Saki at 88.9, and iwo road to Iwo at 90.0. lagos has NaN in both columns: nothing in the reference list reached 80.
Step 5 · Accept strong matches and send the rest to review
Pick a threshold above which you trust the matcher without looking. From the scores above, everything at 92 or more is a plain typo or a reordering, and the 90s mix good matches with Iwo Road. Use 92 for automatic acceptance and send everything else, including names with no suggestion, to a person:
cd ~/fuzzy-demo
cat > triage.py <<'PY'
import pandas as pd
AUTO_ACCEPT = 92
matches = pd.read_csv("matches.csv")
auto = matches["score"] >= AUTO_ACCEPT
accepted = matches[auto].assign(town_clean=matches["suggested"])
accepted[["town_norm", "town_clean"]].to_csv("accepted.csv", index=False)
review = matches[~auto].assign(approved="")
review.to_csv("review.csv", index=False)
print("accepted automatically:", len(accepted))
print("sent to review:", len(review))
print(review.to_string(index=False))
PY
uv run triage.pyA missing score counts as below the threshold (NaN >= 92 is False), so lagos lands in review without a special case.
The right threshold depends on your data, not on this page. Short names are the risk: one wrong letter in a three-letter town such as Iwo or Oyo is a large share of the word. Look at a sample of accepted matches just above your threshold and a sample of review rows just below it, and move the line until the accepted side has no mistakes you would mind.
Check it worked
The script prints accepted automatically: 12 and sent to review: 9. The review table lists ibadan north, ibadn, ife, ilorin kwara, iseyn, iwo road, lagos, oyo town and shaki, each with an empty approved column. accepted.csv has 13 lines: a header and 12 names.
Step 6 · Review the doubtful matches and save the mapping
Open review.csv in a spreadsheet or editor and fill the approved column for every row: the correct name from towns.csv, or none for a place that is not in your list. Ask someone who knows the area if you do not. Two decisions here differ from the suggestion: Iwo Road is in Ibadan, and Lagos is outside the study area.
To follow along with exactly these decisions, write the finished file:
cd ~/fuzzy-demo
cat > review.csv <<'CSV'
town_norm,suggested,score,approved
ibadan north,Ibadan,90.0,Ibadan
ibadn,Ibadan,90.9,Ibadan
ife,Ile-Ife,90.0,Ile-Ife
ilorin kwara,Ilorin,90.0,Ilorin
iseyn,Iseyin,90.9,Iseyin
iwo road,Iwo,90.0,Ibadan
lagos,,,none
oyo town,Oyo,90.0,Oyo
shaki,Saki,88.9,Saki
CSVNow combine the decisions into one file, mapping.csv, that says what each normalised spelling means. The script refuses to run while any row has no decision or names a town that is not in the reference list, and it adds every reference town's own spelling, so a correctly typed Saki matches next time even though nobody typed it this time:
cd ~/fuzzy-demo
cat > save_mapping.py <<'PY'
import sys
from pathlib import Path
import pandas as pd
from clean import normalise
review_file = sys.argv[1]
towns = pd.read_csv("towns.csv")
review = pd.read_csv(review_file)
if review["approved"].isna().any():
raise SystemExit(f"{review_file} still has rows with no decision")
unknown = set(review["approved"]) - set(towns["town"]) - {"none"}
if unknown:
raise SystemExit(f"approved names not in towns.csv: {sorted(unknown)}")
parts = [
pd.DataFrame({"town_norm": towns["town"].map(normalise), "town_clean": towns["town"]}),
review.rename(columns={"approved": "town_clean"})[["town_norm", "town_clean"]],
]
for earlier in ["mapping.csv", "accepted.csv"]:
if Path(earlier).exists():
parts.append(pd.read_csv(earlier))
mapping = pd.concat(parts, ignore_index=True).drop_duplicates().sort_values("town_norm")
clashes = mapping[mapping["town_norm"].duplicated(keep=False)]
if len(clashes):
raise SystemExit(f"one name, two answers:\n{clashes.to_string(index=False)}")
mapping.to_csv("mapping.csv", index=False)
overridden = review[review["approved"] != review["suggested"]]
print("names in mapping:", len(mapping))
print("decisions that differ from the suggestion:", ", ".join(overridden["town_norm"]))
PY
uv run save_mapping.py review.csv
grep -E "^(iwo road|lagos|saki)," mapping.csvdrop_duplicates() removes rows that say the same thing twice (ibadan,Ibadan comes from both the reference list and the accepted matches). If two rows give one spelling different answers, the script stops and shows both, rather than letting a later join pick one at random. Commit mapping.csv to version control next to your analysis: it is a record of human decisions, and it is the slowest part of the work to recreate.
Check it worked
The script prints names in mapping: 25 and decisions that differ from the suggestion: iwo road, lagos. The grep shows iwo road,Ibadan, lagos,none and saki,Saki. Leave one approved cell empty and run it again: it stops with review.csv still has rows with no decision and does not touch mapping.csv.
Step 7 · Clean each batch from the mapping
From now on the mapping does the work. This script normalises a batch, joins it to mapping.csv, writes a cleaned copy, and runs the fuzzy matcher only for spellings the mapping has never seen. Those go to new_names.csv, in the same layout as review.csv:
cd ~/fuzzy-demo
cat > apply_mapping.py <<'PY'
import sys
import pandas as pd
from rapidfuzz import fuzz, process
from clean import normalise
source = sys.argv[1]
towns = pd.read_csv("towns.csv")
choices = {town: normalise(town) for town in towns["town"]}
mapping = pd.read_csv("mapping.csv")
batch = pd.read_csv(source)
batch["town_norm"] = batch["town"].map(normalise)
batch = batch.merge(mapping, on="town_norm", how="left",
validate="m:1", indicator=True)
new_names = sorted(batch.loc[batch["_merge"] == "left_only", "town_norm"].unique())
rows = []
for name in new_names:
best = process.extractOne(name, choices, scorer=fuzz.WRatio, score_cutoff=80)
rows.append({"town_norm": name,
"suggested": best[2] if best else None,
"score": round(best[1], 1) if best else None,
"approved": ""})
pd.DataFrame(rows, columns=["town_norm", "suggested", "score", "approved"]).to_csv(
"new_names.csv", index=False)
out = source.removesuffix(".csv") + "_clean.csv"
batch.drop(columns=["town_norm", "_merge"]).to_csv(out, index=False)
print("rows:", len(batch))
print("matched from mapping:", (batch["_merge"] == "both").sum())
print("new names to review:", ", ".join(new_names) or "none")
print(batch["town_clean"].value_counts(dropna=False).to_string())
PY
uv run apply_mapping.py responses.csvThen run it on December's batch, which repeats some old spellings and brings two new ones:
cd ~/fuzzy-demo
cat > responses_dec.csv <<'CSV'
response_id,town
29,Ibadan
30,Ìbàdàn
31,OGBOMOSO
32,Iwo Road
33,Ilesha
34,Saki
35,Oyo town
36,Iseyin LGA
CSV
uv run apply_mapping.py responses_dec.csv
cat new_names.csvvalidate="m:1" is the same guard as in the joins tutorial: if the mapping ever gets a duplicate spelling, the join stops instead of copying survey rows. Iwo Road now becomes Ibadan without anyone looking at it again, because a person decided that once.
Check it worked
On responses.csv the script prints matched from mapping: 28, new names to review: none and a count of 8 for Ibadan, and responses_clean.csv has a town_clean column next to the original town. On the December batch it prints matched from mapping: 6 and new names to review: ilesha, iseyin lga. new_names.csv suggests Iseyin at 90.0 for iseyin lga and nothing for ilesha.
Step 8 · Fold the new decisions back into the mapping
Review new_names.csv the same way. Ilesha is a real town in Osun State, but it is not in this study's list, so it gets none; if it should be in the study, add it to towns.csv first and approve it there. Iseyin LGA is the local government area around Iseyin, so it maps to Iseyin:
cd ~/fuzzy-demo
cat > new_names.csv <<'CSV'
town_norm,suggested,score,approved
ilesha,,,none
iseyin lga,Iseyin,90.0,Iseyin
CSV
uv run save_mapping.py new_names.csv
uv run apply_mapping.py responses_dec.csvThe loop for every future batch is now: run apply_mapping.py, review whatever lands in new_names.csv, run save_mapping.py new_names.csv. Each round the review list gets shorter.
The same pipeline works for people's names, but the stakes are higher. Two patients called Adebayo Ogunleye and Adebayo Ogunlèye may be one person or two, and merging them wrongly mixes their records. For people, never auto-accept on the name alone: require a second field to agree (date of birth, phone number, a registration ID) and send everything else to review.
Check it worked
save_mapping.py prints names in mapping: 27 and decisions that differ from the suggestion: ilesha. The second apply_mapping.py run prints matched from mapping: 8 and new names to review: none, and responses_dec_clean.csv shows Iseyin LGA cleaned to Iseyin and Ilesha to none. When you have finished, delete the folder with rm -r ~/fuzzy-demo.
Next steps
- Join the cleaned town column to other tables without losing rows: join DataFrames in pandas without losing or duplicating rows.
- Handle the fixed-rule cleaning (types, dates, blanks) before you reach for fuzzy matching: clean a CSV file with pandas.
- Learn more of the string methods
normaliseis built from: work with text strings in Python.
Related tutorials
- Join DataFrames in pandas without losing or duplicating rowsYou will join orders to customers and products with pandas merge, compare the four join types by row count, catch duplicate and mismatched keys with validate= and indicator=, list unmatched rows with an anti-join and stack new batches with concat.
- How to Clean and Summarise a CSV File with pandasYou will take a messy orders CSV with stray spaces, mixed spellings, money written as text, odd dates, missing values and a duplicate row, and clean it with pandas 3.1 on Python 3.15 into a tidy file plus per-country and per-month summaries.
- Work with text: strings, f-strings and Unicode in PythonYou will clean a messy list of names and phone numbers with Python's string methods, format it as an aligned table with f-strings, handle accented names and emoji correctly, and end with a script that writes a clean UTF-8 contact file.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials