Sub topic 7
Deciding by cardinality: when category helps and when it does not
This chapter assumes you can already measure a DataFrame with memory_usage(deep=True) and that you know why an object column of strings is expensive. It also assumes you can convert a column with astype("category"). The question here is which string columns to convert and which to leave alone.
Cardinality is the deciding number
The cardinality of a column is the number of distinct values it holds. A country column with 5 distinct values in 100,000 rows has low cardinality. A session_id column where almost every row differs has high cardinality.
A categorical column stores two things:
- Each distinct value once, in a list of categories.
- One small integer code per row, pointing into that list.
An object column stores one pointer per row (8 bytes) to a Python string object. The string object carries its own overhead, about 49 bytes plus one byte per ASCII character on 64-bit CPython. Check this on your machine:
import sys
print(sys.getsizeof(""))
print(sys.getsizeof("US"))
print(sys.getsizeof("item_000123"))If n is the number of rows and k the number of distinct values, the costs are roughly:
- object:
n * (8 + 49 + len)bytes, counting each row's own string object. - category:
k * (8 + 49 + len)bytes for the categories, plusn * cbytes for the codes, wherecis 1, 2 or 4.
The cost of the categories grows with k. The cost of the codes grows with n. When k is small, the first term is negligible and each row costs c bytes instead of about 60 or more. When k approaches n, you pay for every string plus a code column on top.
The code width grows with the number of categories
pandas picks the smallest signed integer type that can address all the categories.
| Number of categories | Code dtype | Bytes per row |
|---|---|---|
| up to 127 | int8 | 1 |
| 128 to 32,767 | int16 | 2 |
| 32,768 and above | int32 | 4 |
| above about 2.1 billion | int64 | 8 |
Missing values are stored as code -1, so they cost no extra category. You can confirm the code dtype with s.cat.codes.dtype, as in an earlier chapter.
Measuring the effect across cardinalities
The experiment below builds string columns of the same length with growing numbers of distinct values. It compares the deep memory of the object version with the category version.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 100_000
def make_labels(k):
pool = np.array([f"item_{i:06d}" for i in range(k)])
return pd.Series(pool[rng.integers(0, k, n)], dtype="object")
rows = []
for k in [5, 100, 5_000, 50_000, 100_000]:
s = make_labels(k)
obj = s.memory_usage(deep=True, index=False)
cat = s.astype("category").memory_usage(deep=True, index=False)
rows.append({
"requested": k,
"unique": s.nunique(),
"ratio": s.nunique() / len(s),
"object_bytes": obj,
"category_bytes": cat,
"cat_over_obj": cat / obj,
})
print(pd.DataFrame(rows).round(3).to_string(index=False))Exact byte counts depend on your Python and pandas versions, but the shape of the result does not change:
- At 5 and 100 distinct values, the category column is a small fraction of the object column. It is dominated by the codes (1 byte per row).
- At 5,000 distinct values, the savings are still large. The code width has grown to 2 bytes, but the 5,000 strings are cheap compared with 100,000 string references.
- At 50,000 distinct values, the saving is much smaller. Roughly half the rows still hit a unique string, and the codes now take 4 bytes per row.
- At 100,000 requested values, about 63% of the draws are distinct (some values repeat by chance). The category column is close to the object column in size. Any remaining gain is small.
The ratio column is unique / rows. It is the number to watch when you decide.
Break-even in memory terms
Setting the two costs equal gives a simple break-even. Let u = 8 + 49 + len be the cost of one string plus its pointer, and c the code width. Category wins on memory when:
k / n < 1 - c / uYou can compute this directly:
def breakeven_ratio(str_len, code_bytes):
per_string = 8 + 49 + str_len
return 1 - code_bytes / per_string
for str_len in (2, 11, 40):
for code_bytes in (1, 2, 4):
print(str_len, code_bytes, round(breakeven_ratio(str_len, code_bytes), 3))For realistic strings the break-even ratio is above 0.9. Memory alone says convert unless almost every value is unique. Longer strings push the break-even closer to 1, and the savings at a given ratio get larger.
This is only an estimate. It ignores the fixed overhead of the categorical object. It also treats each row's string as a separate Python object. If many rows share one string object, the real RAM of the object column is lower than deep=True reports. deep=True calls sys.getsizeof on every element, so it counts a shared string each time it appears. Always measure your own column rather than trusting the formula.
Why practical rules use a lower threshold
The shrink helper from this tutorial's last chapter converts a column only when nunique() < 0.5 * len(df). That is stricter than the memory break-even. The reasons are practical:
- Small gains do not justify the side effects. Near a ratio of 0.5 the saving is real but moderate. Categorical columns bring behaviors you must handle: unseen values,
groupbyoutput, comparisons and merges. These are covered in the pitfalls chapter. - Building the categories costs time.
astype("category")must find the unique values and map every row to a code. For a high-cardinality column this is slow and produces a large categories index. - Operations may not speed up. Low-cardinality groupings and comparisons are cheap on codes. With many categories, the codes add a layer of indirection and little else.
- The column may change later. A column with 400 values today can have 4 million tomorrow. Keeping the rule conservative avoids surprises.
A reasonable practice is a three-zone rule:
| Unique ratio | Typical decision |
|---|---|
| Below about 5% | Convert. The saving is large and the codes are int8 or int16. |
| About 5% to 50% | Convert if memory is tight. Measure first. |
| Above 50% | Leave as object (or a string dtype). The saving is small. |
These cutoffs are conventions, not laws. Treat them as defaults and change them when measurements disagree.
A decision procedure
The diagram summarizes the steps for one string column.
Comparing by measurement in code
When the ratio falls in the middle zone, test the conversion on a copy. This helper returns the numbers for a decision:
def category_report(s):
as_cat = s.astype("category")
obj_bytes = s.memory_usage(deep=True, index=False)
cat_bytes = as_cat.memory_usage(deep=True, index=False)
return {
"unique_ratio": s.nunique() / len(s),
"code_dtype": str(as_cat.cat.codes.dtype),
"object_bytes": obj_bytes,
"category_bytes": cat_bytes,
"saved_fraction": 1 - cat_bytes / obj_bytes,
}
s = pd.Series(["red", "green", "blue", "green"] * 25_000, dtype="object")
print(category_report(s))Here the ratio is 3 / 100_000, the code dtype is int8, and the saved fraction is large. Run the same function on a column of unique identifiers and the saved fraction drops to near zero. It can even go slightly negative.
Cases where cardinality misleads
Low cardinality does not always mean convert, and high cardinality does not always mean skip.
- Columns you will modify heavily. Assigning a value that is not in the categories raises an error or forces a type change. A column you often update with new values is a poor fit even at low cardinality.
- Columns you concatenate from many sources. If two categorical columns have different category sets,
pd.concatfalls back toobjectand the saving disappears silently. - Short columns. With a few thousand rows the total memory is already small. The conversion adds code complexity for a few kilobytes.
- Columns already stored compactly. If the column uses an Arrow-backed string dtype, the per-object overhead described above does not apply. The saving from category is smaller, so measure before converting.
- Very long strings. Here the benefit is larger than the ratio suggests, so even a 70% unique ratio can still pay off. Only measuring tells you.
- Cardinality that depends on the file. A column measured on a 1,000-row sample can look low cardinality, then grow when you load the full file. Estimate from the whole column, or from a large random sample. Do not use the head of the file.
Estimating cardinality before you load
When the file is too large to load as object, read just the column you want to inspect. Use usecols to read it and nunique() to count:
from io import StringIO
csv = StringIO("id,country,note\n1,US,a\n2,DE,b\n3,US,c\n4,FR,d\n")
col = pd.read_csv(csv, usecols=["country"])["country"]
print(col.nunique(), len(col), col.nunique() / len(col))For a large file, read one column at a time. This keeps memory bounded by the size of one string column, and you decide each column's dtype before the full load.
Summary of the trade-offs
- Category replaces a per-row string reference with a per-row integer code. The saving is large when the same strings repeat many times.
- The saving shrinks as the unique ratio rises, and it is near zero when nearly every row is unique.
- A conservative default converts below a unique ratio of 0.5. Convert always below about 5%.
- Measure with
memory_usage(deep=True)on both versions for the middle cases. Remember thatdeep=Trueoverstates RAM if strings are shared. - Check the downstream behaviors before you commit, especially for columns that will be updated or concatenated.
Exercise
A DataFrame has 2,000,000 rows. Column city has 800 distinct values, each about 10 characters long. Column trip_id has 1,950,000 distinct values, each about 12 characters. Which would you convert to category, what code dtype would city get, and why is the choice different for trip_id?
Show answer
Convert city. It has 800 distinct values, so its unique ratio is 0.0004 and pandas stores its codes as int16 (more than 127 and fewer than 32,768 categories). Each row then costs 2 bytes instead of about 67 bytes (8 for the pointer plus roughly 59 for the string object). The 800 stored strings add almost nothing. trip_id has a unique ratio of 0.975, so nearly every row still needs its own string in the categories list, and the int32 codes (4 bytes per row) are added on top. The saving is small and the conversion is slow, so leave trip_id as it is.
Exercise
Write code that, given a DataFrame df, prints for each object column its unique ratio and the fraction of memory saved by converting it to category, using deep memory on both versions.
Show answer
for col in df.selectdtypes(include="object").columns: s = df[col] obj = s.memoryusage(deep=True, index=False) cat = s.astype("category").memory_usage(deep=True, index=False) print(col, round(s.nunique() / len(s), 4), round(1 - cat / obj, 3))