Clean text and define categories

3.1.1

Normalize text labels and use ordered categoricals for levels with a known order.

On this page

Normalize labels with string methods

Use Series.str methods to trim whitespace, standardize case, and test text. Preserve original labels if you need a record of the changes. When filtering, decide whether a missing label should count as a match.

import pandas as pd

raw = pd.Series([" Coffee ", "tea", None], dtype="string")
clean = raw.str.strip().str.casefold()
print(clean.fillna("unknown").tolist())
print(clean.str.contains("coffee", regex=False, na=False).tolist())
Example output
['coffee', 'tea', 'unknown']
[True, False, False]

Sort using category order

Use a categorical dtype for a known set of labels. Ordered categories sort in their declared order. Unexpected labels become missing when cast to a fixed category list, so check unknown values before casting.

import pandas as pd

levels = pd.Categorical(["high", "low", "medium"], categories=["low", "medium", "high"], ordered=True)
print(pd.Series(levels).sort_values().tolist())
Example output
['low', 'medium', 'high']

Official references