Sub topic 10
When category beats string
This chapter assumes you know what a pandas dtype is, can create Series and DataFrames, and have met the string dtype from the earlier chapters. The question here is when a text column should not be a string column at all.
What category stores
A string column keeps one text value for every row. A category column keeps each distinct value once, in a list called the categories. It then stores a small integer code per row that points into that list.
If a column of 1,000,000 rows holds only 20 different country codes, category stores 20 strings and 1,000,000 small integers. string stores 1,000,000 strings. The more repetition, the bigger the saving.
import pandas as pd
s = pd.Series(["a", "b", "a", "b"] * 1000, dtype="string")
cat = s.astype("category")
print(s.memory_usage(deep=True))
print(cat.memory_usage(deep=True))
print(cat.cat.categories.tolist())
print(cat.cat.codes.head().tolist())The category version is far smaller. cat.cat.categories shows the stored distinct values, and cat.cat.codes shows the integer codes.
Check cardinality first
Cardinality is the number of distinct values. The ratio of distinct values to rows predicts whether category will help.
import pandas as pd
df = pd.DataFrame(
{
"country": ["NO", "PE", "NO", "SE"] * 500,
"note": [f"row {i}" for i in range(2000)],
},
dtype="string",
)
for col in df.columns:
ratio = df[col].nunique() / len(df)
print(col, round(ratio, 3))country prints a ratio of 0.002 and note prints 1.0. A ratio near zero favors category. A ratio near one means almost every value is unique, so the codes plus the category list cost more than plain strings.
A rough rule is to try category when the ratio is below about 0.5. Always confirm with memory_usage(deep=True).
Other reasons to choose category
Memory is not the only reason. A categorical column also gives you:
- A fixed set of allowed values, so a typo stands out.
- An optional order, such as
low < medium < high, which makes sorting and comparison follow the logical order instead of alphabetical order. - Faster
groupbyand comparison operations on repeated values, because pandas works with integer codes.
import pandas as pd
levels = pd.CategoricalDtype(["low", "medium", "high"], ordered=True)
risk = pd.Series(["high", "low", "medium", "low"], dtype=levels)
print(risk.sort_values().tolist())
print((risk >= "medium").tolist())The output is ['low', 'low', 'medium', 'high'] and then [True, False, True, False].
What you give up
A categorical column is less flexible than a string column. Three differences cause most surprises.
- Values must belong to the categories. Assigning an unseen value raises an error. You have to add the category first.
- Text methods work on the categories. The
.straccessor is available only when the categories are strings, and results may not come back as astringcolumn. Convert back withastype("string")when you need text work. - Missing values are not a category. They are stored with a special code and shown as
NaN. They are not counted among the categories.
import pandas as pd
c = pd.Series(["low", "high", "low"], dtype="category")
c = c.cat.add_categories(["medium"])
c.iloc[1] = "medium"
print(c.tolist())
print(c.cat.categories.tolist())Without the add_categories call, the assignment fails because "medium" is not a known category.
A practical workflow
Clean the column while it is string, then convert it at the end. This keeps the .str accessor behavior you already know and applies category only to the final, tidy values.
import pandas as pd
s = pd.Series([" Oslo", "oslo ", "LIMA", "lima", None], dtype="string")
cleaned = s.str.strip().str.lower().astype("category")
print(cleaned.cat.categories.tolist())
print(cleaned.isna().tolist())Cleaning first merges " Oslo" and "oslo " into one value, oslo. The result has only two categories, lima and oslo. Converting before cleaning would have kept spelling variants as separate categories.
Exercise
A DataFrame has 2,000,000 rows. Column status has 4 distinct values. Column order_id has 2,000,000 distinct values. Which column should become category, why, and how do you confirm the choice?
Show answer
Convert status. Its distinct-to-row ratio is tiny, so storing 4 strings plus integer codes is much smaller than 2,000,000 strings. Leave order_id as string, since every value is unique and category would add code overhead without saving anything. Confirm by comparing memory_usage(deep=True) before and after astype("category").