Sub topic 8
Under the hood: categories and integer codes
The previous chapter converted repetitive string columns to category and measured the savings. This chapter explains why that works. It covers the two arrays that make up a categorical column, how the integer codes are chosen, and which operations touch only the small array and which touch every row.
This chapter assumes you can create a Series and a DataFrame, know what int8 and int64 mean, and have run memory_usage(deep=True). No new libraries are needed.
Two arrays instead of one
A categorical column does not hold your strings row by row. It holds two things:
- categories: an
Indexof the distinct values, each stored once. - codes: an integer array with one entry per row. Each entry is a position in the categories index.
To read row i, pandas takes codes[i] and looks up categories[codes[i]].
You can inspect both arrays directly.
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 are DE, FR, US, and the codes are [2, 0, 2, 1, 0, 2]. The codes dtype is int8. The categories are sorted because pandas sorts the unique values when it infers them. The codes refer to positions in that sorted order, not to the order in which values first appeared.
You can rebuild the original values from the two arrays yourself:
restored = s.cat.categories.take(s.cat.codes.to_numpy())
print(list(restored))
print(list(restored) == s.tolist())Index.take picks entries by position, which is the same lookup pandas performs internally. The second line prints True.
Where the memory goes
The cost of a categorical column is:
rows x bytes per code + number of categories x cost of one categoryFor an object column of strings, the cost is one 8-byte pointer per row plus one Python string object per row. Here the Python string objects are the expensive part. A short string object takes roughly 50 bytes on CPython. In a categorical column, the string objects exist only once per distinct value.
Compare the two forms:
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 100_000
countries = rng.choice(["US", "DE", "FR", "JP", "BR"], n)
as_object = pd.Series(countries, dtype=object)
as_cat = as_object.astype("category")
print("object :", as_object.memory_usage(index=False, deep=True))
print("category :", as_cat.memory_usage(index=False, deep=True))
print("codes :", as_cat.cat.codes.nbytes)
print("cats :", as_cat.cat.categories.memory_usage(deep=True))The object column takes several megabytes. The categorical column takes a little over 100,000 bytes. Almost all of that is the codes array: 100,000 rows at 1 byte each. The categories index is tiny by comparison.
The savings come from two changes:
- Per-row storage drops from a pointer plus a string object to one integer.
- The string objects shrink from one per row to one per distinct value.
The exact numbers depend on your Python and pandas versions. Newer pandas releases have a dedicated string dtype with different storage than object, so measure on your own setup instead of reusing figures from this page.
How the code dtype is chosen
Pandas picks the smallest signed integer type that can address every category. It does not use an unsigned type, because one code value is reserved to mean "missing".
| Number of categories | Codes dtype | Bytes per row |
|---|---|---|
| up to 127 | `int8` | 1 |
| up to 32,767 | `int16` | 2 |
| up to about 2.1 billion | `int32` | 4 |
| more than that | `int64` | 8 |
The width grows with the number of categories, not with the number of rows. A column with 100 distinct values uses 1 byte per row whether it has a thousand rows or a billion. A column with 200 distinct values uses 2 bytes per row. This is the main reason the cardinality rules from the previous chapter work: more categories mean wider codes and a bigger categories index.
Missing values are code -1
A missing value is not stored as a category. It is stored as the code -1, which points at nothing.
t = pd.Series(["a", None, "b", "a"], 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, 0], and isna() reports True for the second row. This is also why codes are signed. A negative code can never be a valid position, so it works as a safe marker.
Controlling the category order
When you let pandas infer categories, it sorts them. You can supply your own list instead. The order you give becomes the order of the codes.
sizes = pd.Categorical(
["low", "high", "low", "high"],
categories=["low", "mid", "high"],
)
print(sizes.codes.tolist())
print(sizes.categories.tolist())
print(pd.Series(sizes).value_counts().to_dict())The codes are [0, 2, 0, 2]. The category mid appears in no row, but it stays in the categories index, and value_counts reports it with a count of 0. A category is a declared possible value, not a record of what appears in the data. This is how a categorical column can hold values that no row currently uses.
To reuse one set of categories across several columns or DataFrames, build a CategoricalDtype once:
country_dtype = pd.CategoricalDtype(["BR", "DE", "FR", "JP", "US"])
a = pd.Series(["US", "DE"], dtype=country_dtype)
b = pd.Series(["FR", "US", "JP"], dtype=country_dtype)
print(a.cat.codes.tolist(), b.cat.codes.tolist())
print(a.dtype == b.dtype)Both series use the same code assignment (US is always 4). The dtypes compare equal, which keeps later comparisons and concatenations cheap and predictable. Passing such a dtype to read_csv, as in dtype={"country": country_dtype}, gives the same result at load time.
Which operations touch codes and which touch categories
Knowing the layout tells you what a categorical operation costs.
Operations on the categories array cost time proportional to the number of distinct values, not the number of rows:
renamed = s.cat.rename_categories({"US": "United States"})
print(renamed.cat.categories.tolist())
print(renamed.cat.codes.tolist())The output shows the categories as ['DE', 'FR', 'United States'] and the codes unchanged at [2, 0, 2, 1, 0, 2]. Pandas renamed one entry in the small index. It did not rewrite the per-row data. On an object column, the same change would visit every row.
Equality tests work the same way. For s == "US", pandas finds which code "US" has, then compares the integer codes. Comparing integers is faster than comparing strings. Operations such as value_counts and groupby can also count by code and attach the labels at the end.
Operations that must produce one value per row, such as s.astype(str) or s.str.upper(), expand the codes back into real strings. They allocate a full-size column of strings, so they temporarily lose the memory savings. Assigning the result back to a categorical column re-compresses it, but the peak memory use still happens.
small = s[s == "US"]
print(small.cat.categories.tolist())
trimmed = small.cat.remove_unused_categories()
print(trimmed.cat.categories.tolist())The first line prints all three categories. The second prints only ['US']. This matters when you split a large DataFrame into many small ones, because each piece carries the full categories index.
Why codes are not stable labels
The integer codes are an internal detail. They depend on the category order, which depends on how the column was built or modified. Two columns holding the same strings can have different codes if their categories differ.
x = pd.Series(["US", "DE"], dtype="category")
y = pd.Series(["US", "FR"], dtype="category")
print(x.cat.codes.tolist(), y.cat.codes.tolist())Here US has code 1 in x (categories DE, US) and code 1 in y (categories FR, US) by coincidence of sorting. Add a BR row to y and its US code becomes 2. Do not save codes to disk, join on them, or compare them across columns. Compare the labels, or give the columns one shared CategoricalDtype first.
The next chapter covers the practical pitfalls that follow from this layout: assigning values that are not in the categories, grouping with unused categories, and comparing columns whose categories differ.
Summary of the model
- A categorical column is a codes array (one small signed integer per row) plus a categories index (one entry per distinct value).
- Code width follows the number of categories:
int8up to 127,int16up to 32,767, and so on. - Missing values are code
-1, not a category. - Category order is either inferred (sorted) or set by you, and it defines the codes.
- Operations on categories are cheap. Operations that rebuild strings for every row are not.
Exercise
A column has 1,000,000 rows and 300 distinct country-region labels, and no missing values. You convert it to category. What dtype do the codes use, and how many bytes does the codes array occupy? Does the answer change if the column has 10,000,000 rows?
Show answer
300 categories is more than 127, so pandas uses int16 (2 bytes per code). The codes array takes 1,000,000 x 2 = 2,000,000 bytes. With 10,000,000 rows the dtype stays int16 because it depends on the number of categories, not rows. The codes array grows to 20,000,000 bytes.
Exercise
You run s = pd.Series(["b", "a", None, "b"], dtype="category"). What are s.cat.categories and s.cat.codes.tolist()?
Show answer
The categories are ['a', 'b'] because pandas sorts the distinct non-missing values. The codes are [1, 0, -1, 1]. "b" is at position 1, "a" at position 0, and the missing value is code -1.