Sub topic 3
Categories, codes, and the .cat accessor
This chapter assumes you can create pandas Series and DataFrames, know dtypes such as int64 and object, and have used value_counts. You will learn what a categorical Series holds internally and how to inspect it through the .cat accessor.
Two arrays behind one column
A categorical column stores two things:
- categories: the list of distinct values the column may contain, each stored once.
- codes: one small integer per row. Each code is the position of that row's value in the categories list.
Pandas shows you the original labels, but it works on the integer codes internally.
import pandas as pd
s = pd.Series(["small", "large", "medium", "small", "large", None], dtype="category")
print(s.dtype)
print(list(s.cat.categories)) # ['large', 'medium', 'small']
print(s.cat.codes.tolist()) # [2, 0, 1, 2, 0, -1]
print(s.cat.ordered) # FalseWhen pandas infers the categories from the data, it sorts them. Here large gets code 0, medium gets 1, and small gets 2. The missing value gets the code -1. A missing value is never a category. It is marked by that code.
What the .cat accessor offers
.cat is a namespace that exists only on categorical Series. Calling it on an object column raises an AttributeError, so convert first with astype("category").
| Attribute or method | What it gives you |
|---|---|
| `s.cat.categories` | The categories, as an `Index` |
| `s.cat.codes` | The integer codes, as a Series with a small integer dtype such as `int8` |
| `s.cat.ordered` | `True` if the categories have a logical order |
| `s.cat.add_categories`, `remove_categories`, `rename_categories`, `reorder_categories`, `set_categories` | Edit the category list (covered in a later chapter) |
You can also build a categorical straight from codes. This is useful when data arrives already encoded.
import pandas as pd
cat = pd.Categorical.from_codes(
[2, 0, 1, 2, -1],
categories=["large", "medium", "small"],
)
s = pd.Series(cat)
print(s.tolist()) # ['small', 'large', 'medium', 'small', nan]Why the details matter
The codes are positions, not permanent IDs. If the category list changes order, the same label can get a different code. Do not store codes and reuse them later without also storing the categories.
Categories are defined by the dtype, not by the data. A category can have zero rows. Slicing or filtering a categorical keeps all the categories, even ones that no longer appear:
import pandas as pd
s = pd.Series(["a", "b", "c"], dtype="category")
subset = s[s != "c"]
print(list(subset.cat.categories)) # ['a', 'b', 'c']
print(subset.value_counts().to_dict()) # {'a': 1, 'b': 1, 'c': 0}This is why value_counts shows a row with count 0 for c. It also affects groupby, which a later chapter covers.
Common errors
- Calling
.caton a column that is stillobjectdtype. - Treating
cat.codesas stable across different Series. Two Series can use the same labels with different category orders, so their codes will not match. - Forgetting that
-1means missing. Using codes as numeric features without handling-1treats missing data as a real value that sorts below everything else. - Expecting removed rows to remove categories. Use
remove_unused_categories()when you want that.
Exercise
A Series s = pd.Series(["b", "a", "b", None], dtype="category") is created. What are list(s.cat.categories) and s.cat.codes.tolist()?
Show answer
The categories are ['a', 'b'] because inferred categories are sorted. The codes are [1, 0, 1, -1]: b is at position 1, a is at position 0, and the missing value gets -1.