Sub topic 6
Converting Repetitive Strings to category
This chapter covers converting string columns with many repeated values to pandas' category dtype. It assumes you can create and index DataFrames, know the basic dtypes (int64, float64, object), and have measured memory with memory_usage(deep=True).
Why this conversion matters
A column of country codes with five distinct values and 100,000 rows is stored as an object column by default. Each row holds a pointer to a Python string object, so the column pays for a pointer per row plus the string objects themselves. The same text appears many times, and pandas does not know it can share it.
The category dtype fixes this. It stores each distinct value once, in a list called the categories. It then stores one small integer per row, called a code, that says which category the row uses.
Measuring the baseline
Build a sample DataFrame and measure it with deep=True. The default shallow count only counts the pointers in an object column, not the string objects they point to, so it understates the real cost.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 100_000
df = pd.DataFrame({
"user_id": rng.integers(0, 50_000, n),
"age": rng.integers(18, 90, n),
"score": rng.random(n),
"country": rng.choice(["US", "DE", "FR", "JP", "BR"], n),
})
print(df.dtypes)
print(df.memory_usage(deep=True))
print(df.memory_usage(deep=True).sum())On a typical 64-bit build, country is the largest column. The three numeric columns use 8 bytes per row, which is 800,000 bytes each. The country column uses 8 bytes per row for the pointers plus the string objects counted by deep=True. With NumPy-backed object columns, that is several times larger than a numeric column. Exact numbers vary by pandas and Python version, so run the code and read your own output.
Converting with astype
Use astype("category") to convert a column.
df["country"] = df["country"].astype("category")
print(df["country"].dtype)
print(df["country"].cat.categories)
print(df["country"].cat.codes.dtype)
print(df.memory_usage(deep=True))The output shows three things:
- The dtype is
category. - The categories are the five distinct strings, sorted.
- The codes use
int8, because five categories fit easily in one byte.
The country column now costs about 1 byte per row, or roughly 100,000 bytes plus a small fixed amount for the categories. That is a reduction of more than 90 percent for this column.
The .cat accessor exposes categorical features. .cat.categories is the list of distinct values. .cat.codes is the per-row integer array.
How pandas picks the code dtype
Pandas chooses the smallest signed integer type that can index the categories:
| Number of categories | Code dtype | Bytes per row |
|---|---|---|
| Up to 127 | int8 | 1 |
| 128 to 32,767 | int16 | 2 |
| 32,768 to 2,147,483,647 | int32 | 4 |
| More than that | int64 | 8 |
A missing value is stored as code -1, which is why the codes are signed. Missing values are not a category themselves. They stay as NaN when you read the column.
Deciding by cardinality
Cardinality is the number of distinct values in a column. The saving from category depends on the ratio of distinct values to rows.
The cost of a categorical column is roughly:
- the codes: rows × code size
- plus the categories: one stored copy of each distinct value
The cost of an object column is roughly rows × (pointer size + string object size), minus whatever sharing Python already did.
When most values are distinct, the categories list is nearly as large as the original data, and you also pay for the codes. The conversion then costs more memory than it saves. A column of unique email addresses, UUIDs, or free-text comments is a poor fit.
You can check the ratio before converting:
ratio = df["country"].nunique() / len(df)
print(ratio)For country this is 0.00005. A common rule of thumb is to convert when the ratio is below about 0.5, and the helper function later in this tutorial uses that threshold. Treat it as a starting point. Strings that are long and repeated a lot, such as job titles, save the most. Very short strings with moderate repetition may save little, so measure before and after.
What categories change about behavior
A categorical column is not just a smaller string column. Several behaviors differ, and they cause most of the bugs people hit.
Values outside the categories
You cannot assign a value that is not already a category.
s = pd.Series(["a", "b", "a"], dtype="category")
try:
s[0] = "z"
except (TypeError, ValueError) as e:
print(type(e).__name__, e)
s = s.cat.add_categories(["z"])
s[0] = "z"
print(s)The first assignment raises an error. Add the category first, then assign. The same applies to fillna with a new value and to concatenating two categorical columns that have different categories. In the concatenation case, pandas falls back to object unless the categories match, which silently removes your memory savings. Use pd.api.types.union_categoricals or set the same categories on both sides first.
groupby and unobserved categories
When you group by a categorical column, pandas can include categories that have no rows. In older pandas versions this was the default. The observed argument controls it.
means = df.groupby("country", observed=True)["score"].mean()
print(means)With observed=True, only categories present in the data appear. With observed=False, every category appears, with NaN or zero for empty ones. When you group by two categorical columns, observed=False builds the full cross product, which can be very large. Set observed=True explicitly so your result does not depend on the pandas version.
Ordering and comparisons
By default, a categorical is unordered. You can test equality, but < and > raise an error. Sorting uses the order of the categories, not alphabetical order of the values, once you set a custom order.
sizes = pd.Series(["small", "large", "medium", "small"])
ordered = pd.Categorical(
sizes, categories=["small", "medium", "large"], ordered=True
)
s = pd.Series(ordered)
print(s.sort_values().tolist())
print((s > "small").tolist())This gives you a meaningful order for values like sizes or ratings. Comparing against a value that is not a category raises an error.
Operations that lose the dtype
Some operations convert the column back to object, such as certain string methods through .str, apply on elements, and merge between columns with different categories. After any such step, check df.dtypes.
Categories and index alignment
When you convert and then join on a categorical key, both sides should use identical categories. Otherwise pandas compares values after converting to object, which is slower and uses more memory during the operation. The simplest approach is to build one CategoricalDtype and apply it to both frames.
from pandas.api.types import CategoricalDtype
country_type = CategoricalDtype(["US", "DE", "FR", "JP", "BR"])
left = pd.DataFrame({"country": ["US", "DE"]}).astype({"country": country_type})
right = pd.DataFrame({"country": ["DE", "US"], "n": [1, 2]}).astype(
{"country": country_type}
)
merged = left.merge(right, on="country")
print(merged.dtypes)A shared dtype also keeps the codes stable across files, so the same string always maps to the same integer.
Seeing the savings
Compare the two representations directly:
obj = pd.Series(rng.choice(["US", "DE", "FR", "JP", "BR"], n))
cat = obj.astype("category")
print(obj.memory_usage(deep=True), cat.memory_usage(deep=True))Now try a high-cardinality column:
ids = pd.Series([f"user-{i}" for i in range(n)])
print(ids.memory_usage(deep=True), ids.astype("category").memory_usage(deep=True))The first pair shows a large reduction. The second pair shows the categorical column as larger than the original, since every value is distinct and the codes are extra.
Common errors
- Assigning a new value fails. Add the category with
cat.add_categories, or convert back toobject. - Memory grows after a concat or merge. The categories differed, so pandas produced
object. Share oneCategoricalDtype. - A groupby returns rows you did not expect. Unobserved categories are included. Pass
observed=True. - Comparison raises a
TypeError. The categorical is unordered, or the value is not a category. - No savings. The column has high cardinality, or short strings that were already cheap.
Exercise
A DataFrame has 1,000,000 rows. Column city has 400 distinct values. Column order_id has 1,000,000 distinct strings. Which should you convert to category, which code dtype will pandas use for the converted column, and how would you confirm the choice?
Show answer
Convert city. Its ratio of distinct values to rows is 0.0004, so each string is stored once and the rows hold small codes. With 400 categories, which is more than 127 and fewer than 32,768, pandas uses int16 codes (2 bytes per row). Leave order_id as it is, since every value is distinct and the categories list would be as large as the original data plus the codes. Confirm by comparing df[col].memory_usage(deep=True) before and after astype("category") for each column, and by checking df["city"].cat.codes.dtype.
Exercise
You run pd.concat([a, b]) where a["country"] and b["country"] are both categorical, but b contains a country that a lacks. What happens to the dtype, and how do you keep it as category?
Show answer
The result is object, because the categories differ, so the memory savings are lost. To keep category, give both columns the same CategoricalDtype before concatenating, or combine them with pd.api.types.union_categoricals.