TExcelTAD
Home › pandas › Categorical Data

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

python · try it yourself
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:

python · try it yourself
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:

python · try it yourself
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:

python · try it yourself
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

python · try it yourself
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 category for 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"?

  1. Because it is categorical
  2. Because plain strings sort alphabetically
  3. Because of missing values
  4. Because sort_values is broken

What happens when you convert "B+" to a categorical whose categories are A, B, AB, O?

  1. It becomes "B"
  2. It becomes NaN
  3. A new category is added
  4. It stays as text

What is the main memory advantage of the category dtype?

  1. Values are compressed with zip
  2. Each distinct label is stored once, rows store small integer codes
  3. Categories are stored on disk
  4. There is no advantage