Categorical Data
Many columns hold a small, fixed set of labels: T-shirt sizes, ticket priorities, blood types, weekdays. pandas has a dedicated category dtype for them. It saves memory, can enforce a custom sort order (so "S < M < L" instead of alphabetical), and rejects values that aren't in the allowed set.
Converting to category
import pandas as pd
orders = pd.DataFrame({
"order": range(1, 9),
"size": ["M", "S", "XL", "M", "L", "S", "M", "L"],
})
orders["size"] = orders["size"].astype("category")
print(orders["size"].dtype)
print(orders["size"].cat.categories.to_list())
print(orders["size"].cat.codes.to_list())category
['L', 'M', 'S', 'XL']
[1, 2, 3, 1, 0, 2, 1, 0]
Internally pandas stores each label once (the categories) plus a small integer code per row. That's why categories use so little memory for long columns with few distinct values. The .cat accessor exposes the details.
Ordered categories
Sorting the plain text would give L, M, S, XL (alphabetical), which is meaningless for sizes. A CategoricalDtype with ordered=True defines the real order:
import pandas as pd
size_type = pd.CategoricalDtype(["S", "M", "L", "XL"], ordered=True)
orders = pd.DataFrame({
"order": range(1, 9),
"size": ["M", "S", "XL", "M", "L", "S", "M", "L"],
})
orders["size"] = orders["size"].astype(size_type)
print(orders.sort_values("size")["size"].to_list())
print(orders[orders["size"] >= "L"]["order"].to_list())
print(orders["size"].max())['S', 'S', 'M', 'M', 'M', 'L', 'L', 'XL']
[3, 5, 8]
XL
With an order, comparisons like >= "L" and max() make sense too.
Counting with all categories
value_counts() and groupby() on a categorical column list every category, even those with zero rows. That's often exactly what a report needs:
import pandas as pd
rating_type = pd.CategoricalDtype(["poor", "fair", "good", "great"], ordered=True)
reviews = pd.Series(["good", "great", "good", "fair", "great", "good"], dtype=rating_type)
print(reviews.value_counts(sort=False))
df = pd.DataFrame({"rating": reviews, "helpful": [3, 10, 1, 0, 7, 2]})
print(df.groupby("rating", observed=False)["helpful"].sum())poor 0
fair 1
good 3
great 2
Name: count, dtype: int64
rating
poor 0
fair 0
good 6
great 17
Name: helpful, dtype: int64
poor has no reviews but still appears with 0. Pass observed=True to groupby to hide empty categories.
Values outside the categories
A value that isn't one of the categories can't be stored. When converting, it becomes NaN; when assigning, pandas raises an error. This is a cheap form of validation:
import pandas as pd
blood = pd.CategoricalDtype(["A", "B", "AB", "O"])
donors = pd.Series(["A", "O", "B+", "AB"]).astype(blood)
print(donors)
try:
donors[0] = "Z"
except (TypeError, ValueError) as err:
print("Rejected:", err)0 A
1 O
2 NaN
3 AB
dtype: category
Categories (4, object): ['A', 'B', 'AB', 'O']
Rejected: Cannot setitem on a Categorical with a new category (Z), set the categories first
Changing categories
import pandas as pd
priority = pd.Series(["lo", "hi", "mid", "lo"], dtype="category")
priority = priority.cat.rename_categories({"lo": "low", "mid": "medium", "hi": "high"})
print(priority.cat.categories.to_list())
priority = priority.cat.reorder_categories(["low", "medium", "high"], ordered=True)
print(priority.sort_values().to_list())
priority = priority.cat.add_categories(["urgent"])
print(priority.cat.categories.to_list())['high', 'low', 'medium']
['low', 'low', 'medium', 'high']
['low', 'medium', 'high', 'urgent']
| Method | Does |
|---|---|
cat.categories / cat.codes |
the labels / integer codes |
cat.rename_categories() |
rename labels |
cat.reorder_categories() |
set a new order |
cat.add_categories() / cat.remove_categories() |
change the allowed set |
cat.remove_unused_categories() |
drop labels with no rows |
cat.as_ordered() |
mark as ordered |
Tip: Use
categoryfor columns with few distinct values that repeat a lot. For columns where almost every value is unique (names, emails), it saves nothing and only adds complexity.
Test yourself
Why might df["size"].sort_values() put "XL" last but "L" before "M"?
- Because it is categorical
- Because plain strings sort alphabetically
- Because of missing values
- Because sort_values is broken
What happens when you convert "B+" to a categorical whose categories are A, B, AB, O?
- It becomes "B"
- It becomes NaN
- A new category is added
- It stays as text
What is the main memory advantage of the category dtype?
- Values are compressed with zip
- Each distinct label is stored once, rows store small integer codes
- Categories are stored on disk
- There is no advantage