Sub topic 10
When category beats string
The string dtype is the right default for text, but some text columns hold only a handful of distinct values repeated many times. Country codes, order statuses, and product tiers are examples. For these columns the category dtype can use far less memory and speed up grouping. This chapter explains how category stores data, when it wins, when it loses, and what to watch for when you switch.
This chapter assumes you can create Series and DataFrames, know what a dtype is, and have read the earlier chapters on the string dtype, missing values, and storage backends.
How category stores text
A string column stores one text value per row. A category column splits the data in two:
- A list of the distinct values, called the categories, stored once.
- An array of small integers, called the codes, with one code per row. Each code is a position in the categories list.
A million rows that repeat three words need three strings and a million tiny integers, not a million strings.
import pandas as pd
s = pd.Series(["a", "b", "a", None, "b"], dtype="string")
cat = s.astype("category")
print(cat.cat.categories)
print(cat.cat.codes.tolist())
print(cat.isna().tolist())The categories are a and b, and the codes are [0, 1, 0, -1, 1]. The code -1 marks a missing value. A missing value is never a category, so it does not appear in cat.cat.categories, and isna() still finds it.
Measuring the saving
The saving depends on how often values repeat. Measure with memory_usage(deep=True), which counts the memory used by the values themselves, not just the pointers to them.
import pandas as pd
def report(values):
s = pd.Series(values, dtype="string")
cat = s.astype("category")
print(f"unique ratio: {s.nunique() / len(s):.4f}")
print("string :", s.memory_usage(deep=True))
print("category:", cat.memory_usage(deep=True))
report(["a", "b", "a", "b"] * 1000)
report([f"user-{i}" for i in range(4000)])The first call repeats two values 4,000 times. The category column is much smaller. The second call has 4,000 distinct values. Here the category column is not smaller and is often larger, because it stores every string in the categories list and also a code for every row.
The unique ratio, the number of distinct values divided by the number of rows, is a quick first test. A ratio near zero favors category. A ratio near one rules it out.
The string dtype with the pyarrow backend is already more compact than the python backend. That narrows the gap, so category wins by less than it would against a Python-backed column. It still tends to win when repetition is heavy. Measure with your own backend instead of assuming.
Decision criteria
| Situation | Better choice | Reason |
|---|---|---|
| Few distinct values, many rows | `category` | Each string is stored once. |
| Nearly every value is unique | `string` | Categories plus codes cost more than plain storage. |
| Free-form text such as comments or names | `string` | Repetition is low and you will run `.str` methods. |
| The values have a meaningful order (`S` < `M` < `L`) | ordered `category` | Sorting and comparison follow the declared order. |
| You need a fixed list of allowed values | `category` | The categories act as a schema. |
| The set of values keeps changing | `string` | New values must be added to the categories first. |
| Many joins or concatenations with other frames | usually `string` | Mismatched categories cause surprises, covered below. |
Speed is a second reason to choose category. Grouping and comparing integer codes is generally cheaper than hashing and comparing strings. It is not guaranteed, so time your own operation before you commit.
Converting and declaring categories
astype("category") infers the categories from the data and sorts them. If you know the full set in advance, declare it with pd.CategoricalDtype. This keeps values that do not occur in the data, and it fixes the order.
import pandas as pd
size_type = pd.CategoricalDtype(["S", "M", "L"], ordered=True)
size = pd.Series(["M", "S", "L", "S"], dtype=size_type)
print(size.sort_values().tolist())
print((size >= "M").tolist())The sort gives S, S, M, L, which follows the declared order. A string column would sort L, M, S, S. The comparison size >= "M" gives [True, False, True, False]. A string column cannot compare in this meaningful way.
Values that are not in the declared categories become missing when you convert. If you convert a column with a typo such as "XL" using the dtype above, that entry becomes a missing value without raising an error. Check isna().sum() before and after.
Working with text in a category column
The .cat accessor manages the categories. The common methods are:
cat.cat.categorieslists the categories.cat.cat.codesreturns the integer codes.cat.cat.add_categories([...])adds allowed values.cat.cat.remove_unused_categories()drops categories that no row uses.cat.cat.rename_categories({...})renames a category everywhere at once.
Renaming is a strong reason to use category. The rename changes the categories list, not every row, so it is cheap on a large column.
A category column whose categories are strings also supports the .str accessor. The work is done on the categories list, which is shorter than the column. Even so, .str is designed for the string dtype. If a column needs heavy cleaning, splitting, or regex work, clean it as string first and convert to category as the last step.
Gotchas
Assigning a value that is not a category
A category column accepts only values from its categories. Add the value first.
import pandas as pd
s = pd.Series(["a", "b"], dtype="category")
try:
s[0] = "z"
except (TypeError, ValueError) as err:
print("rejected:", type(err).__name__)
s = s.cat.add_categories("z")
s[0] = "z"
print(s.tolist())This strictness is useful when the categories are a schema, because bad data fails loudly. It is a nuisance when the data changes often.
Unused categories in groupby
A group-by on a category column can include categories that have no rows. This is controlled by the observed argument.
import pandas as pd
df = pd.DataFrame(
{
"country": pd.Categorical(
["NO", "PE", "NO"], categories=["NO", "PE", "SE"]
),
"sales": [10, 20, 5],
}
)
print(df.groupby("country", observed=False)["sales"].sum())
print(df.groupby("country", observed=True)["sales"].sum())With observed=False the result has a row for SE with a sum of 0. With observed=True only NO and PE appear. Older pandas versions defaulted to False and pandas 3 defaults to True. Pass the argument explicitly so your code gives the same result on both.
Concatenating columns with different categories
Combining two category columns that have different categories does not give a category column. pandas falls back to object, which loses the memory saving and the type.
import pandas as pd
from pandas.api.types import union_categoricals
a = pd.Series(["x", "y"], dtype="category")
b = pd.Series(["y", "z"], dtype="category")
print(pd.concat([a, b]).dtype)
combined = pd.Series(union_categoricals([a, b]))
print(combined.dtype)
print(combined.tolist())The first line prints object. union_categoricals builds one shared categories list and keeps the category dtype. Merges and joins have a similar issue when the key columns have different categories, so keep the dtype identical on both sides when you can.
Sorting uses category order, not alphabet
sort_values on a category column sorts by the order of the categories. For an unordered category that order is the one inferred or declared, which is alphabetical only when pandas inferred it from sortable strings. If you declared ["S", "M", "L"], that is the sort order. This is usually what you want, but it surprises people who expected alphabetical sorting.
Arithmetic and string operations on the column itself
A category column of strings is not a string column. Joining two columns with + does not work as it does for string. If you need a derived text column, convert with astype("string") first, build the new value, and convert back if needed.
Choosing in practice
Follow this sequence when you are unsure:
- Compute
s.nunique() / len(s). If it is above roughly 0.5, stay withstring. This threshold is a rule of thumb, not a pandas rule. - If the ratio is low, compare
memory_usage(deep=True)forstringandcategoryusing the backend you actually run. - Consider whether the values are a fixed set or have an order. If so, declare a
CategoricalDtype. - Do all text cleaning on the
stringcolumn, then convert tocategory. - Pass
observed=Trueorobserved=Falseexplicitly in every groupby.
Exercise
A DataFrame has 2 million rows. The column status has 4 distinct values. The column email has about 1.9 million distinct values. Which column should become category, and which should stay string? Name one measurement you would take to confirm the choice.
Show answer
Convert status to category and keep email as string. status has a unique ratio near zero, so storing four strings plus small integer codes is far smaller than 2 million strings. email has a unique ratio near one, so a category would store almost every string in the categories list and add a code per row. To confirm, compare memory_usage(deep=True) for the string and category versions of each column, using the storage backend you run in production.
Exercise
You run this code and the result has an unexpected object dtype. What went wrong and how do you fix it?
import pandas as pd
a = pd.Series(["x", "y"], dtype="category")
b = pd.Series(["y", "z"], dtype="category")
print(pd.concat([a, b]).dtype)
Show answer
The two Series have different categories (x, y and y, z). When categories differ, pd.concat falls back to object. To keep a category dtype, use pd.Series(union_categoricals([a, b])) from pandas.api.types, or declare the same CategoricalDtype with all allowed values on both Series before combining them.