Find a course

Module 3: Fixing Values and TypesLesson 6 of 1214 min

Cleaning Text and Standardizing Categories

Fix whitespace, case and spelling variants, build mapping tables, use fuzzy matching with care, and catch invisible characters that break grouping.

Step 1 of 10Learn

Five spellings of one city

A delivery company wanted to know which city had the most late deliveries. The chart showed Chicago first, with 1,840 late orders. The real winner was New York, but its 2,600 late orders were split across "New York", "new york", "NYC", "New York " (with a trailing space) and "N.Y.". Each fragment was smaller than Chicago.

To a computer, these are five different strings. Grouping, counting, joining and filtering all compare strings exactly, character by character, including spaces and capitalization. One stray space is enough to create a new category.

Text cleaning is the process of making equivalent values identical. It usually happens in layers, from mechanical to judgment-based:

  1. Whitespace: remove leading and trailing spaces and collapse repeated inner spaces.
  2. Case: convert to one case, typically lowercase, for comparison.
  3. Punctuation and symbols: remove or standardize periods, hyphens and quotes when they don't carry meaning.
  4. Synonyms and abbreviations: map "nyc" and "n.y." to "new york" with an explicit lookup table.
  5. Fuzzy matches: catch typos such as "new yrok" with similarity measures, then review.

The first three are safe to automate. The last two need human judgment, because similar strings do not always mean the same thing.

Late deliveries: New York only wins once its five spellings are mergedChicago1,840New York (merged)2,600Unmerged, each New York fragment was smaller than Chicago

Step 2 of 10Learn

Mapping tables: the reliable workhorse

After the mechanical steps, the remaining variants are usually a manageable list. The most reliable fix is a mapping table: a small two-column file that lists each raw variant and its standard value.

rawstandard
nycNew York
n.y.New York
new york cityNew York
sfSan Francisco
san franSan Francisco

Mapping tables have big advantages over clever code. They are explicit: anyone can read and correct them, including colleagues who don't program. They are reusable: next month's export runs through the same table. And they are auditable: if a mapping is wrong, you can see exactly which one.

Build the table from the value counts of the column after mechanical cleaning. Start with the most frequent variants, since a few mappings often cover most rows. For anything left unmapped, decide on a policy: keep it as it is and flag it for review, or map it to "Other". Never silently drop unmapped rows.

When new data arrives, list the values that are not in the table. A new variant appearing ("Nueva York") is caught immediately instead of quietly becoming its own category.

A text standardization pipelineRawvalueTrim +lowercaseMappingtableFuzzy match+ reviewStandardvalue

Step 3 of 10Practice · Code challenge · Python

Write normalize_label(text, mapping). First make a comparison key: collapse all runs of whitespace to single spaces, strip the ends and lowercase it. If the key is in mapping (a dict whose keys are already clean lowercase strings), return the mapped value; otherwise return the cleaned key itself so it can be reviewed.

Real Python, running in a sandbox in your browser.
  • normalize_label(" New York ", {"new york": "New York", "nyc": "New York"})
  • normalize_label("NYC", {"new york": "New York", "nyc": "New York"})
  • normalize_label(" Boston", {"new york": "New York"})
  • normalize_label("san\tfran", {"san fran": "San Francisco"})

Step 4 of 10Practice · Fill in the blanks

Fill in the blanks

In Python, `" Chicago ".() removes the spaces at both ends, and "CHICAGO".()` converts the text to lowercase so that comparisons ignore case.

Step 5 of 10Learn

Fuzzy matching, with a human in the loop

Typos don't appear in any mapping table until someone adds them. Fuzzy matching finds strings that are similar but not identical. The classic measure is edit distance (Levenshtein distance): the minimum number of single-character insertions, deletions or substitutions to turn one string into another. "Chicgo" is one edit from "Chicago"; "kitten" is three edits from "sitting".

A typical workflow compares every unmapped value with the list of known standard values and proposes the closest match if the distance is small, for example at most 2, or if a similarity score is above about 90%.

The danger is that similar strings can mean different things. "Austria" and "Australia" are two edits apart. "Jon Smith" and "Joan Smith" are one edit apart and may be different people. Short strings are the worst: "CA" and "GA" are one substitution apart and are different states.

So treat fuzzy matches as suggestions, not decisions. Generate a list of proposed pairs with their scores, review it, and move the accepted pairs into the mapping table. The mapping table stays the single source of truth, and the fuzzy matcher becomes a tool for growing it faster.

Step 6 of 10Practice · Work it out

What is the edit distance (Levenshtein distance) between "color" and "colour"?

Step 7 of 10Note

Step 8 of 10Learn

Categories: rare levels, combined fields and free text

Once spelling is consistent, look at the structure of each category column.

Rare levels. A product category column may have 40 values, 35 of which cover less than 1% of rows each. For charts and many models, group rare levels into "Other", but do it with a documented threshold, and keep the original column so the detail isn't lost.

Combined fields. Some columns pack two variables together: "M25-34", "Size: L / Color: Red", "Smith, Anna". Split them into separate columns, often with a regular expression. A pattern like ^(M|F|X)_(\d+)-(\d+)$ captures sex, lower age and upper age from "M25-34" and, just as usefully, fails on any value that doesn't follow the expected format, which reveals the exceptions.

Free text. Fields like "reason for return" contain anything people type. Don't try to clean them like categories. Either leave them as text, or code them into a small set of categories with clear rules, a review step and an "uncoded" bucket.

Consistent labels across tables. If one table says "Electronics" and another says "electronics & tech", a join on category will miss rows. Standardize in both places using the same mapping table.

Structural problems in category columnsCategory columnRare levelsgroup as OtherCombinedsplit with regexFree textleave or codeAcross tablessame mapping

Step 9 of 10Practice · Spot the mistake

A colleague built this mapping table for a "city" column of US customer addresses, all of which should map to New York City. Click the mapping that is wrong.

Step 10 of 10Practice · Choose one

Why should you convert text to a single case and strip spaces before building a mapping table?