सामग्री पर जाएँ

लेसन 14 · Types, Text and Dates

Standardizing Categories

Standardize messy category values with mapping tables, review unknown values, suggest matches safely, handle rare categories and keep allowed lists current.

A categorical column should hold values from a limited list: country, status, department, product type. When people type them freely, one category splinters into many. Shipped, shipped , SHPD and Sent then appear as four separate bars in a chart.

Look at all the values

Count every distinct value, sorted by frequency. Read the whole list if it is short.

Python List raw categories with counts

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two layers: normalize, then map

First apply mechanical cleanup (trim, casefold, remove stray punctuation). Then use a mapping table from cleaned variants to official values. The mapping holds meaning, so a person who knows the domain should approve it.

Python Apply a mapping and report unknowns

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Lost? is not forced into a category. It is labeled UNMAPPED and reported. Never use a fallback such as "Other" for values you have not looked at. New spellings, and real new categories, would vanish into it.

Keep the mapping as data

Put mappings in a file or table with columns like these:

raw_value standard_value reason approved_by
shpd Shipped Warehouse abbreviation Operations
sent Shipped Same event in the old system Operations

This invented example shows the format. A table is easy to review and compare between versions, and non-programmers can propose changes. Check that each raw value appears only once, so it cannot map to two things.

Suggest, do not auto-apply

Similarity matching can propose mappings for new values. Python's difflib.get_close_matches returns the closest allowed values.

Python Suggest matches for a person to confirm

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Spelling similarity catches typos but not meaning: it cannot know that HR stands for Human Resources. It can also be badly wrong: "Austria" and "Australia" look alike. Review suggestions before you add them.

Use standard code lists

For countries, currencies and languages, prefer recognized codes such as ISO 3166 (countries), ISO 4217 (currencies) and ISO 639 (languages). Take the lists from a maintained, trustworthy source, and decide how to handle historical or disputed entries according to your organization's rules.

Granularity and hierarchy

Mixed levels are a common trap: a location column that holds Europe, France and Paris. Mapping them into one list does not help. Split them into columns for region, country and city, and leave missing what you do not know.

Rare categories

For charts or models you may group rare values into "Other". Do this in the analysis, not in the cleaned source, and state the threshold. Otherwise you lose detail you may need later.

pandas categories

Python pandas: map and restrict categories

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A categorical type records the allowed values. Canceled appears with a count of zero, which is useful in reports. A value outside the list does not survive the conversion as itself. It has typically become missing, and pandas 3.0 deprecated this behavior with a plan to raise an error in a future version. Check for unmapped values before converting, as the code does, and make sure only allowed or missing values reach the conversion.

Stop new variants

Offer a controlled list in forms, add a database constraint or lookup table, and run your unmapped report on every load. When a new real category appears, update the list on purpose.

Common mistake: merging categories that sound similar but mean different things, such as "Canceled" and "Refunded". Ask the people who create the records what each value means.

Ask what the categories mean

Before you write a mapping, collect a short definition for each official value. "Shipped" might mean the parcel left the warehouse, or that a label was printed. Two systems can use the same word for different events. If you merge them without noticing, counts will mix two things and nobody will see it in the table.

Definitions also help with new values. When Held appears, you can ask whether it fits an existing definition or needs a new category. That is a business decision, and your code should make it visible rather than make it silently.

Maintain the mapping

A mapping table grows over time. A few habits keep it healthy:

  • Give each raw key only one standard value.
  • Store the normalized key, and normalize new input the same way before the lookup.
  • Make sure each standard value is on the allowed list, with a test that fails otherwise.
  • Record when entries were added and why.
  • Do not delete old entries only because they stopped appearing, since you may need to rebuild old data.

Sometimes the right value depends on another column. The same abbreviation might mean different things in two sources. In that case, add the source to the lookup key instead of forcing one meaning everywhere.

History can change

Categories get renamed, split and merged. Before you remap old records, decide whether reports should show what was true at the time or today's grouping. Keep the original code so you can produce either view. Write the choice down next to the report, because two reasonable choices can give different totals for the same period.

Report coverage

On each run, report the share of rows that mapped successfully and the most frequent unmapped values. A sudden fall in coverage is an early warning that a source changed its codes. It is much easier to fix on the day it happens than months later, when someone asks why a category shrank.

Hand over the list

Share the final list of official values and their definitions with the people who enter data. When they can see what each value means, they are more likely to choose the right one.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. What should happen to a value that is not in the mapping?

    Reporting unknowns catches new spellings and new real categories.
  2. 2. What is the safe role of fuzzy suggestions?

    Similar spelling does not guarantee the same meaning.
  3. 3. Where should you usually group rare categories into Other?

    Grouping at analysis time keeps the detail available for other uses.

Summary

  • Count every variant before you change anything.
  • Normalize mechanically, then apply an approved mapping table.
  • Flag unknown values instead of hiding them.
  • Use standard codes and separate mixed levels.

Next: Cleaning Dates and Times

आपकी प्रगति इसी ब्राउज़र में सेव होती है। खाते की ज़रूरत नहीं है।