Blog Open the app

Fuzzy Matching in Pandas: A Practical Guide with Runnable Code

August 9, 2026 · 12 min read · Written by Sam Kale

df.merge() needs identical keys. Real-world data never has them. You have Acme Corp. in one DataFrame and ACME Corporation in another, and Pandas cheerfully returns zero matches.

This guide is the practical fix: how to fuzzy-match two Pandas DataFrames, how to deduplicate a single one, how to score similarity across multiple columns, and how to keep the whole thing fast on hundreds of thousands of rows. Every code block is copy-runnable.

If you're comparing libraries at a higher level, start with our FuzzyWuzzy vs RapidFuzz vs Dedupe comparison. This post assumes you've picked RapidFuzz (you should) and want to know how to use it inside Pandas.

What's in this guide

  1. Setup: install and import
  2. The 3 fuzzy operations you'll actually do
  3. Fuzzy-merging two DataFrames
  4. Deduplicating one DataFrame
  5. Fuzzy matching on multiple columns
  6. Making it fast: blocking & RapidFuzz cdist
  7. A complete fuzzy dedup pipeline
  8. 5 pitfalls that catch everyone
  9. FAQ

Setup: Install and Import

You need three packages. Pandas you already have; the other two are lightweight.

pip install pandas rapidfuzz networkx

Standard imports:

import pandas as pd
from rapidfuzz import fuzz, process, utils
import networkx as nx

The 3 Fuzzy Operations You'll Actually Do

Ninety percent of Pandas fuzzy work reduces to three operations. Learn these and everything else is composition.

1. Score one string against another

>>> fuzz.token_set_ratio("Acme Corp.", "ACME Corporation")
100

>>> fuzz.WRatio("Acme Corp.", "ACME Corporation")
95

RapidFuzz scorers return 0–100. WRatio is a good general-purpose default; token_set_ratio is best when the same words appear in different order or with extra tokens.

2. Find best match of one string against a list

choices = ["Acme Corporation", "Google LLC", "Amazon.com Inc"]

>>> process.extractOne("Acme Corp.", choices, scorer=fuzz.WRatio)
('Acme Corporation', 95.0, 0)   # (match, score, index)

>>> process.extract("Acme Corp.", choices, scorer=fuzz.WRatio, limit=2)
[('Acme Corporation', 95.0, 0), ('Amazon.com Inc', 47.0, 2)]

3. Score every string in one list against every string in another (the workhorse)

import numpy as np

left  = ["Acme Corp.", "Global Ltd", "Widget Co"]
right = ["ACME Corporation", "Widget Company", "Zebra LLC"]

matrix = process.cdist(left, right, scorer=fuzz.WRatio)

>>> matrix
array([[95.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0., 95.,  0.]])

process.cdist is the function you'll use most. It returns a NumPy matrix of shape (len(left), len(right)) where cell [i, j] is the score of left[i] against right[j]. Vectorized, multi-threaded, fast.

Fuzzy-Merging Two DataFrames

Say you have a CRM export and an event attendee list. Same companies, different spellings. You want the equivalent of df1.merge(df2, on='company', how='left'), but tolerant of variation.

import pandas as pd
from rapidfuzz import fuzz, process
import numpy as np

crm = pd.DataFrame({
    'crm_id':  [1, 2, 3, 4],
    'company': ['Acme Corp.', 'Global Widgets Ltd', 'Zenith Industries', 'Momentum LLC'],
    'owner':   ['alice', 'bob',    'carol', 'dan'],
})

leads = pd.DataFrame({
    'lead_id': [10, 11, 12, 13],
    'company': ['ACME Corporation', 'Global Widget', 'Zenith Ind.', 'Nova Systems'],
    'email':   ['a@acme.com', 'b@gw.com', 'c@zen.com', 'd@nova.com'],
})

def fuzzy_merge(left, right, left_on, right_on, threshold=80,
                scorer=fuzz.WRatio, how='left'):
    """Fuzzy equivalent of df.merge() on a single string column."""
    left_vals  = left[left_on].fillna('').astype(str).tolist()
    right_vals = right[right_on].fillna('').astype(str).tolist()

    scores = process.cdist(left_vals, right_vals, scorer=scorer)
    best_idx = scores.argmax(axis=1)
    best_score = scores.max(axis=1)

    matched = right.iloc[best_idx].reset_index(drop=True)
    matched['_score'] = best_score
    matched.loc[best_score < threshold, right.columns] = np.nan

    return pd.concat([left.reset_index(drop=True), matched], axis=1)

result = fuzzy_merge(crm, leads, left_on='company', right_on='company', threshold=80)
print(result[['crm_id', 'company', 'lead_id', 'email', '_score']])

Output:

   crm_id             company  lead_id       email  _score
0       1          Acme Corp.     10.0  a@acme.com    95.0
1       2  Global Widgets Ltd     11.0    b@gw.com    90.0
2       3   Zenith Industries     12.0   c@zen.com    86.0
3       4        Momentum LLC      NaN         NaN    52.0

Momentum LLC didn't have a good match, so its right-hand columns are NaN — exactly how you'd want a left-join to behave. Adjust the threshold to control strictness.

WRatio vs token_set_ratio: WRatio is a weighted combination of several sub-scorers, tuned for general similarity. token_set_ratio is better when word order or extra tokens are the main variation. For company names, WRatio wins most of the time; for free-text address matching, token_set_ratio.

Deduplicating One DataFrame

Self-fuzzy-match with a twist: you want groups of duplicates, not just pairs. If A matches B and B matches C, all three should end up in one group even if A and C don't score above threshold directly.

import pandas as pd
from rapidfuzz import fuzz, process
import numpy as np
import networkx as nx

df = pd.DataFrame({
    'id':      [1, 2, 3, 4, 5, 6],
    'company': ['Acme Corp.', 'ACME Corporation', 'Acme Inc',
                'Global Widgets', 'Global Widgets Ltd', 'Nova Systems'],
})

def fuzzy_dedup(df, col, threshold=85, scorer=fuzz.WRatio):
    vals = df[col].fillna('').astype(str).tolist()
    scores = process.cdist(vals, vals, scorer=scorer)

    n = len(vals)
    triu = np.triu_indices(n, k=1)
    pairs = [(i, j) for i, j in zip(*triu) if scores[i, j] >= threshold]

    G = nx.Graph()
    G.add_nodes_from(range(n))
    G.add_edges_from(pairs)

    groups = np.zeros(n, dtype=int)
    for group_id, component in enumerate(nx.connected_components(G)):
        for idx in component:
            groups[idx] = group_id

    df = df.copy()
    df['dup_group'] = groups
    return df

deduped = fuzzy_dedup(df, col='company', threshold=85)
print(deduped)

# id             company  dup_group
#  1          Acme Corp.          0
#  2    ACME Corporation          0
#  3            Acme Inc          0
#  4      Global Widgets          1
#  5  Global Widgets Ltd          1
#  6        Nova Systems          2

To pick one survivor per group and drop the rest:

# Keep the record with the longest name (typically the most complete)
survivors = (
    deduped
    .assign(_len=deduped['company'].str.len())
    .sort_values('_len', ascending=False)
    .drop_duplicates('dup_group', keep='first')
    .drop(columns='_len')
)

Pick your survivor rule based on the data: most orders, most recent update, longest name, non-null email — whatever makes the survivor the "most complete" record.

Fuzzy Matching on Multiple Columns

Real-world matching usually needs more than one field. Company + city + email is a common trio for B2B lead deduplication.

def multi_col_fuzzy_merge(left, right, key_cols, weights,
                          threshold=80, scorer=fuzz.WRatio):
    """
    Fuzzy match on multiple columns with weights.
    key_cols: list of tuples [(left_col, right_col), ...]
    weights: list of floats that sum to 1.0
    """
    n_left, n_right = len(left), len(right)
    combined = np.zeros((n_left, n_right))

    for (lc, rc), w in zip(key_cols, weights):
        lv = left[lc].fillna('').astype(str).tolist()
        rv = right[rc].fillna('').astype(str).tolist()
        combined += w * process.cdist(lv, rv, scorer=scorer)

    best_idx = combined.argmax(axis=1)
    best_score = combined.max(axis=1)

    matched = right.iloc[best_idx].reset_index(drop=True)
    matched.columns = [f'match_{c}' for c in matched.columns]
    matched['_score'] = best_score
    matched.loc[best_score < threshold, matched.columns] = np.nan

    return pd.concat([left.reset_index(drop=True), matched], axis=1)


result = multi_col_fuzzy_merge(
    crm_df, leads_df,
    key_cols=[('company','company'), ('city','city'), ('email','email')],
    weights=[0.5, 0.2, 0.3],
    threshold=75,
)

Weight tuning is more art than science. Start with 0.5/0.3/0.2 for name/email/geo, then adjust based on how many false positives vs false negatives you see. See Fuzzy Match on Multiple Columns for the full reasoning.

Making It Fast: Blocking & RapidFuzz cdist

process.cdist is fast — typically 1–5 million comparisons per second on a modern laptop — but O(n2) still catches up eventually. Rough performance:

Rows (each side)Comparisonscdist time (est.)
1,0001M< 1 s
10,000100M30–60 s
50,0002.5B15–30 min
200,00040BHours — use blocking

Blocking means grouping rows by a fast exact key first, then running the expensive fuzzy comparison only within each group.

from rapidfuzz.distance import Indel
import unicodedata

def normalize(s):
    if pd.isna(s): return ''
    s = unicodedata.normalize('NFKD', str(s)).encode('ascii', 'ignore').decode()
    return s.lower().strip()

def block_key(s):
    """First 3 characters of normalized name."""
    n = normalize(s)
    return n[:3]

df['_block'] = df['company'].apply(block_key)

pairs = []
for block, group in df.groupby('_block'):
    if len(group) < 2:
        continue
    vals = group['company'].fillna('').astype(str).tolist()
    scores = process.cdist(vals, vals, scorer=fuzz.WRatio)
    idx = group.index.tolist()
    for i in range(len(idx)):
        for j in range(i+1, len(idx)):
            if scores[i, j] >= 85:
                pairs.append((idx[i], idx[j], scores[i, j]))

pairs_df = pd.DataFrame(pairs, columns=['idx_a', 'idx_b', 'score'])

Blocking on the first 3 characters typically shrinks a 100k-row self-join by 100–500x. For non-English or transliterated data, use a SOUNDEX-style code or Metaphone as the block key instead.

Blocking recall trade-off: every blocking scheme misses some real duplicates (records whose block keys differ). To recover them, run 2–3 different blocking passes with different keys (first-3-chars, SOUNDEX, first token) and union the pair sets. This is standard practice in libraries like dedupe.io.

A Complete Fuzzy Dedup Pipeline

Putting it all together: normalize, block, fuzzy-score, cluster, pick survivors. This is a self-contained script you can adapt.

import pandas as pd
import numpy as np
import networkx as nx
import unicodedata
from rapidfuzz import fuzz, process

def normalize(s):
    if pd.isna(s): return ''
    s = unicodedata.normalize('NFKD', str(s)).encode('ascii', 'ignore').decode()
    s = s.lower().strip()
    for suffix in [' inc', ' llc', ' ltd', ' corp', ' corporation', ' co.', ' gmbh']:
        if s.endswith(suffix):
            s = s[:-len(suffix)]
    return s.strip()

def dedup_pipeline(df, col, threshold=85, block_len=3, scorer=fuzz.WRatio):
    df = df.copy()
    df['_norm']  = df[col].apply(normalize)
    df['_block'] = df['_norm'].str[:block_len]

    pairs = []
    for _, group in df.groupby('_block'):
        if len(group) < 2:
            continue
        vals = group['_norm'].tolist()
        idx = group.index.tolist()
        m = process.cdist(vals, vals, scorer=scorer)
        n = len(vals)
        for i in range(n):
            for j in range(i+1, n):
                if m[i, j] >= threshold:
                    pairs.append((idx[i], idx[j], float(m[i, j])))

    G = nx.Graph()
    G.add_nodes_from(df.index)
    G.add_edges_from((a, b) for a, b, _ in pairs)

    groups = np.full(len(df), -1)
    for gid, comp in enumerate(nx.connected_components(G)):
        for idx in comp:
            groups[df.index.get_loc(idx)] = gid

    df['dup_group'] = groups
    return df, pd.DataFrame(pairs, columns=['idx_a', 'idx_b', 'score'])


df = pd.read_csv('accounts.csv')
deduped, pairs_df = dedup_pipeline(df, col='company', threshold=85)

# Auto-merge threshold: 92+; manual review band: 85-92
pairs_df['action'] = np.where(pairs_df['score'] >= 92, 'auto_merge', 'review')
pairs_df.to_csv('candidate_pairs.csv', index=False)

survivors = (
    deduped
    .sort_values('_norm', key=lambda s: s.str.len(), ascending=False)
    .drop_duplicates('dup_group', keep='first')
    .drop(columns=['_norm', '_block', 'dup_group'])
)
survivors.to_csv('deduped_accounts.csv', index=False)

This is genuinely production-ready code for datasets up to a few hundred thousand rows. Beyond that, either switch to SQL with pg_trgm or move to a dedicated tool like dedupe.io or Splink.

5 Pitfalls That Catch Everyone

  1. Not normalizing before scoring. RapidFuzz scores raw strings. If you compare "Acme Corp." to "acme corp" without lowering case, you leak a few points of score to noise. Always run a normalize step first (case-fold, strip punctuation, strip legal suffixes, trim whitespace).
  2. Forgetting fillna(''). A NaN in your string column will throw a TypeError inside RapidFuzz. Always .fillna('').astype(str) before passing to a scorer.
  3. Using fuzz.ratio when you want fuzz.WRatio. fuzz.ratio is a pure Levenshtein-based scorer — it penalizes length differences heavily. WRatio is a smart blend that handles length differences and word reordering. For company/name matching, WRatio is almost always right.
  4. Running an unblocked self-join at 100k+ rows. It works in the notebook on a sample, hangs in production on the full data. Always add a blocking key before you scale up.
  5. Trusting argmax when the true match isn't in the right frame. fuzzy_merge above returns the best match for every left row, whether or not that best match is actually a duplicate. The threshold filter fixes this — but only if you keep it strict. Tune on labeled data or eyeball a random sample of 50 pairs.

FAQ

Can I use Pandas merge_asof for fuzzy string matching?

No. merge_asof is for nearest-numeric or nearest-timestamp joins (as-of joins in time-series analysis). It doesn't understand string similarity. Use the fuzzy_merge pattern above with RapidFuzz for fuzzy string joins.

What about the fuzzy_pandas or pandas-dedupe libraries?

fuzzy_pandas is a thin wrapper over FuzzyWuzzy that hasn't been updated in years. pandas-dedupe is a thin wrapper around dedupe.io and is more of a convenience for the active-learning workflow — useful if you want a human-in-the-loop labeler. For direct control, RapidFuzz + Pandas is cleaner.

How do I fuzzy match with Polars instead of Pandas?

The core RapidFuzz functions work identically — just use pl.Series.to_list() to feed a column into process.cdist, then wrap the result back into Polars. Polars' native performance advantage is on filtering and aggregation, not the fuzzy scoring itself, so runtime is dominated by RapidFuzz either way.

What about using sentence-transformers / embeddings for matching?

Embedding-based matching is much better than string similarity for semantic equivalence ("Big Blue" = "IBM") but much slower and requires GPU for real-time scoring. For most company/customer/vendor dedup, RapidFuzz + a good normalize step gets 95% of the accuracy at 1000x the throughput. Reach for embeddings only when you have semantic aliases that no string metric can catch.

How do I export the pairs to a CSV for manual review?

The dedup_pipeline function above returns a pairs_df with idx_a, idx_b, and score. Join it back to the original DataFrame to attach names and other context, then .to_csv(...) for a human reviewer. Sort by score descending so the highest-confidence pairs are at the top.

What if my DataFrame is too big to fit in memory?

Two options: (a) do the blocking step in chunks with pd.read_csv(chunksize=100000), or (b) push the whole pipeline to SQL. Once you're past 1M rows, warehouse-native fuzzy matching (Postgres pg_trgm, Snowflake JAROWINKLER) is almost always faster than Pandas.

Wrapping Up

Fuzzy matching in Pandas isn't complicated once you know the three primitives: fuzz.WRatio for scoring, process.cdist for vectorized bulk comparison, and networkx.connected_components for clustering. Everything else is composition and tuning.

Save the pipeline function above, tune the threshold on your data, and you have a reusable dedup workflow that scales cleanly from prototype to production. When you outgrow it, you'll know: the runtime will start to bite, and that's when you move to SQL or a dedicated matching tool.

Related Reading

Not ready to write Python for a one-off dedup? DedupFuzzy runs the same normalize + block + fuzzy-score pipeline in your browser. Upload CSV, pick columns, tune weights, download survivors. Free for 500 rows.

Try DedupFuzzy Free