Sub topic 8
Under the hood: categories and integer codes
This chapter assumes you can build a pandas Series, you know the category dtype from the previous chapters, and you know that integer dtypes have fixed sizes. It explains how a categorical column is stored, so the memory savings and the behavior you see later make sense.
Two arrays instead of one
An object column holds one Python string reference per row. A categorical column splits that into two parts:
- categories: an index of the distinct values, stored once.
- codes: an array of small integers, one per row. Each code is a position in the categories.
import pandas as pd
s = pd.Series(["US", "DE", "US", "FR", "DE", "US"], dtype="category")
print(s.cat.categories)
print(s.cat.codes.tolist())
print(s.cat.codes.dtype)The categories come out sorted as DE, FR, US. The codes are [2, 0, 2, 1, 0, 2], because US is at position 2, DE at 0 and FR at 1. The codes use int8, so each row costs one byte.
How pandas picks the code dtype
Pandas uses the smallest signed integer type that can address every category. A signed type is used so that the value -1 can mark missing data.
| Number of categories | Code dtype | Bytes per row |
|---|---|---|
| up to 127 | int8 | 1 |
| up to 32,767 | int16 | 2 |
| up to 2,147,483,647 | int32 | 4 |
| more than that | int64 | 8 |
The code dtype grows with the number of categories, so a column with many distinct values pays more per row. That is why high-cardinality columns save little.
Seeing the savings
The saving comes from replacing many string references with one-byte codes plus a short categories index.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
values = rng.choice(["US", "DE", "FR", "JP", "BR"], 100_000)
as_object = pd.Series(values, dtype="object")
as_category = as_object.astype("category")
print(as_category.cat.codes.dtype)
print("object: ", as_object.memory_usage(deep=True))
print("category:", as_category.memory_usage(deep=True))The category version is roughly 100,000 bytes for the codes, plus a few hundred bytes for the five labels. The object version needs 8 bytes per reference plus the string objects themselves.
Missing values use code -1
A missing value is not added to the categories. Pandas stores it as the code -1.
t = pd.Series(["a", None, "b"], dtype="category")
print(t.cat.categories.tolist())
print(t.cat.codes.tolist())
print(t.isna().tolist())The categories are ['a', 'b'], the codes are [0, -1, 1], and isna() reports the middle row as missing.
Rebuilding the labels yourself
Using the categories as a lookup table reproduces the original values. This is what pandas does when you read a label from the column.
labels = s.cat.categories.take(s.cat.codes)
print(labels.tolist())
print(labels.tolist() == s.tolist())Index.take is used here instead of plain indexing. It is the safe choice, and it matches what pandas does internally. Do not index with categories[codes] if the column has missing values. A code of -1 would then select the last category instead of meaning "missing".
What this means in practice
- Operations on categories run on the codes. Operations such as
groupby,value_countsand equality tests can work on small integers. They are often faster than on strings. - Adding a new category changes the index, not the codes. Existing codes keep their meaning, and new values get the next free position.
- Unused categories still occupy the index. After you filter rows, the categories that no longer appear stay in the dtype until you call
remove_unused_categories().
subset = s[s == "US"]
print(subset.cat.categories.tolist())
subset = subset.cat.remove_unused_categories()
print(subset.cat.categories.tolist())The first print still shows all three categories. The second shows only US.
Common errors
- Assuming codes are values. Codes are positions. A code of
2means "the third category", not the number 2. - Comparing codes across columns. Two categorical columns can map the same code to different labels. Compare labels, not codes.
- Expecting a sort by label. Unless the categories are ordered, sorting follows the category order, which is only alphabetical when pandas builds it from the data.
Exercise
A categorical column has 40,000 distinct labels and 10 million rows. Which dtype do the codes use, and roughly how many bytes do the codes take in total?
Show answer
The codes use int32, because 40,000 exceeds the int16 limit of 32,767. With 4 bytes per row, 10 million rows need about 40 million bytes (40 MB) for the codes, plus the categories index.
Exercise
A categorical Series contains ["a", None, "b"]. What are its codes, and why is -1 used?
Show answer
The codes are [0, -1, 1]. The value -1 marks a missing entry, because missing values are not stored as categories and a signed integer type can hold -1.