Sub topic 3
Categories, codes, and the .cat accessor
A pandas categorical column does not store your strings row by row. It stores a short list of the distinct values, called categories, and one small integer per row that points into that list. Knowing this layout explains most categorical behavior, including the quirks that surprise people later.
This chapter assumes you can create and index Series and DataFrames, know dtypes such as int64 and object, and have used value_counts. It covers the data model and the .cat accessor. Memory measurements, ordering, and category editing get their own chapters, so they appear here only briefly.
The two parts of a categorical
A categorical has two pieces:
- Categories are the allowed values, kept in an
Index. Each category appears once. - Codes are an array of integers, one per row. Code
kmeans "the value at positionkin the categories". The special code-1means missing.
The dtype also records whether the categories have a meaningful order (ordered=True or False). Together, the categories and the ordered flag make up a CategoricalDtype.
Looking inside a categorical
Convert a column with astype("category") or pass dtype="category" to the constructor. Then use the .cat accessor to see both parts.
import pandas as pd
s = pd.Series(["small", "large", "medium", "small", "large"], dtype="category")
print(s.dtype) # category
print(s.cat.categories.tolist()) # ['large', 'medium', 'small']
print(s.cat.codes.tolist()) # [2, 0, 1, 2, 0]
print(s.cat.ordered) # False
print(s.cat.codes.dtype) # int8Three details are worth noting:
- When pandas infers the categories, it sorts the unique values. Here the order is alphabetical, so
smallgets code 2 even though it is the "smallest" size. That is why an ordered categorical needs an explicit category list, which a later chapter covers. - Codes use the smallest signed integer type that fits the number of categories. That is
int8for up to 127 categories, thenint16, and so on. This is where much of the memory saving comes from. .cat.codesreturns a Series with the same index as the original..cat.categoriesreturns anIndexwith a different length.
The relationship is a plain lookup. You can rebuild the values from the two parts with pd.Categorical.from_codes, which also works as a constructor when you already have codes:
import pandas as pd
cats = ["large", "medium", "small"]
codes = [2, 0, 1, 2, -1]
c = pd.Categorical.from_codes(codes, categories=cats)
print(c.tolist()) # ['small', 'large', 'medium', 'small', nan]
print(c.codes.tolist()) # [2, 0, 1, 2, -1]from_codes validates the codes. Any code that is below -1 or at or above len(cats) raises a ValueError.
The .cat accessor
The .cat accessor exists only on Series with a categorical dtype. Calling .cat on an object or int64 Series raises AttributeError: Can only use .cat accessor with a 'category' dtype. That error is a quick way to check that a column really converted.
| Member | Kind | What it gives you |
|---|---|---|
| `.cat.categories` | attribute | The `Index` of allowed values |
| `.cat.codes` | attribute | Integer codes as a Series, with `-1` for missing |
| `.cat.ordered` | attribute | `True` if the categories have a logical order |
| `.cat.as_ordered()` / `.cat.as_unordered()` | method | Copy with the ordered flag changed |
| `.cat.add_categories()` | method | Copy with extra allowed values |
| `.cat.remove_categories()` | method | Copy without some categories. Affected rows become missing |
| `.cat.remove_unused_categories()` | method | Copy without categories that no row uses |
| `.cat.rename_categories()` | method | Copy with new names, with the same codes |
| `.cat.reorder_categories()` | method | Copy with the same categories in a new order |
| `.cat.set_categories()` | method | Copy with an exact new list. Values outside it become missing |
Every method returns a new Series. None of them changes the original, so assign the result back. A later chapter covers when each method is safe to use.
Only listed values are allowed
The category list is a closed set. A value that is not in it cannot be stored. When you build a categorical with a fixed dtype, such values become missing instead of raising an error.
import pandas as pd
level = pd.CategoricalDtype(["low", "mid", "high"])
t = pd.Series(["low", "extreme", "high"], dtype=level)
print(t.tolist()) # ['low', nan, 'high']
print(t.cat.codes.tolist()) # [0, -1, 2]The typo or unexpected value "extreme" is silently replaced by NaN with code -1. This is useful for cleaning, because you can see exactly which rows did not match. It is also a common source of data loss. After converting with an explicit dtype, check that t.isna().sum() equals the number of missing values you had before.
Assigning into an existing categorical follows a different rule. s.iloc[0] = "huge" raises a TypeError mentioning "Cannot setitem on a Categorical with a new category". You must add the category first.
Categories belong to the dtype, not to the data
A categorical keeps its full category list even when no row uses some of the categories. Filtering rows does not shrink the list.
import pandas as pd
s = pd.Series(["small", "large", "medium", "small", "large"], dtype="category")
sub = s[s != "large"]
print(sub.cat.categories.tolist()) # ['large', 'medium', 'small']
print(sub.value_counts().to_dict()) # {'small': 2, 'medium': 1, 'large': 0}large is still a category, so value_counts reports it with a count of 0. This is helpful when you want complete tables with every level shown. It can also surprise you in plots, in groupby results, and in nunique()-style checks. Use .cat.remove_unused_categories() when you want the list to match the data. The groupby chapter returns to this behavior.
s.nunique() counts the distinct values that actually occur in the data. len(s.cat.categories) counts the allowed values. These two numbers can differ.
Dtype identity and comparison
CategoricalDtype objects compare by content:
import pandas as pd
a = pd.CategoricalDtype(["x", "y"])
b = pd.CategoricalDtype(["y", "x"])
c = pd.CategoricalDtype(["x", "y"], ordered=True)
print(a == b) # True: unordered, same set of categories
print(a == c) # False: different ordered flag
print(a == "category") # True: matches the string formFor unordered dtypes, the order of the list does not matter for equality. For ordered dtypes it does. Two Series with different category lists have different dtypes, and this has consequences when you combine them. For example, pd.concat of two categorical columns with different categories falls back to object. A later chapter shows how to prevent that by giving both columns the same dtype object.
A string such as "category" as the dtype means "infer the categories from the data". Passing the same CategoricalDtype instance to several columns or DataFrames is the safest way to keep them consistent.
What happens to the values in everyday operations
Because the values live behind a lookup, many operations work on the categories, not on every row. Some examples:
- String methods:
s.str.upper()works on a categorical of strings. The result is a categorical again, because pandas transforms the categories and keeps the codes. - Comparisons:
s == "small"works for unordered categoricals if the scalar is in the categories. Comparing to a value outside the categories gives all-Falsefor==and raises for<and>. For unordered categoricals,<and>raise aTypeErrorin all cases. - Sorting:
s.sort_values()sorts by code, which means by category order, not alphabetical order of the values. For inferred categories those two orders are the same. For a custom list they are not. - Arithmetic: a categorical of numbers does not support
+ormean(). Convert withastype(float)first. - Conversion back:
s.astype(object)ors.astype(str)gives ordinary values, ands.to_numpy()returns the values as an array, not the codes.
A quick check you can reuse
Before relying on a categorical column, print this summary. It exposes the common problems at once: unexpected nulls, unused categories, or a wrong ordered flag.
import pandas as pd
def describe_categorical(s: pd.Series) -> None:
cats = s.cat.categories
print("dtype: ", s.dtype)
print("ordered: ", s.cat.ordered)
print("categories:", cats.tolist())
print("codes dtype:", s.cat.codes.dtype)
print("missing: ", int((s.cat.codes == -1).sum()))
unused = [c for c in cats if c not in set(s.dropna())]
print("unused: ", unused)
s = pd.Series(["a", "b", None, "a"], dtype=pd.CategoricalDtype(["a", "b", "z"]))
describe_categorical(s)The output reports one missing value and z as unused. The missing count comes from the -1 code. That is the same count s.isna().sum() gives, but the codes make the storage rule visible.
Exercise
Given s = pd.Series(["b", "a", None, "b"], dtype="category"), what are s.cat.categories and s.cat.codes.tolist()? What would s.cat.codes.tolist() be after s = s.cat.add_categories(["c"])?
Show answer
The categories are ['a', 'b'] (sorted, with the missing value excluded), and the codes are [1, 0, -1, 1]: "b" is position 1, "a" is position 0, and the missing value is -1. Adding the category "c" appends it at the end of the list, so the existing codes do not change and stay [1, 0, -1, 1].
Exercise
A column is converted with astype(pd.CategoricalDtype(["low", "mid", "high"])). Before the conversion it had 0 nulls, and afterward it has 4. What happened, and how do you find the offending rows?
Show answer
Four values were not in the category list ("Low" with different capitalization, a typo, or whitespace), so they became NaN with code -1. Find them by keeping the original column and filtering it with the mask converted.isna(), for example df.loc[converted.isna(), "original"].unique().