Sub topic 7
Deciding by cardinality: when category helps and when it does not
This chapter assumes you can build DataFrames, read dtypes such as object and int64, and have used memory_usage(deep=True). Earlier chapters showed that category shrinks repetitive string columns. Here you decide when it is worth using.
What cardinality means
Cardinality is the number of distinct values in a column. A country column with five values across 100,000 rows has low cardinality. A column of email addresses where every row differs has cardinality equal to the row count.
A categorical column stores two things:
- A table of the distinct values, kept once.
- One small integer code per row that points into that table.
The savings depend on how many rows share each value. When many rows repeat the same value, the codes are far cheaper than one string reference per row. When few rows repeat, you still pay for the codes and also for the table, so you save little or nothing.
Measuring the ratio
The useful number is the unique ratio: distinct values divided by row count. Compute it with nunique().
import numpy as np
import pandas as pd
rng = np.random.default_rng(1)
n = 100_000
df = pd.DataFrame({
"country": rng.choice(["US", "DE", "FR", "JP", "BR"], n),
"user_code": [f"user-{i}" for i in range(n)],
"city": [f"city-{i}" for i in rng.integers(0, 20_000, n)],
})
for col in df.columns:
ratio = df[col].nunique() / len(df)
print(f"{col}: {df[col].nunique()} unique, ratio {ratio:.4f}")Expect a ratio near 0.00005 for country, about 0.18 for city, and exactly 1.0 for user_code.
Comparing the actual cost
Do not guess. Convert each column and compare the memory both ways.
for col in df.columns:
as_object = df[col].memory_usage(deep=True)
as_category = df[col].astype("category").memory_usage(deep=True)
print(f"{col}: object={as_object:,} category={as_category:,}")country drops sharply, because the five strings are stored once and the codes need one byte each. city also shrinks, since each of its 20,000 or so values is shared by several rows. user_code does not shrink. Every value is unique, so the category stores all 100,000 strings in its table and adds a code for each row. The result is larger than the original.
A rule of thumb
A common cutoff is a unique ratio below 0.5, which is the default in the shrink helper you will build later. Treat it as a starting point. The real saving also depends on string length. Long strings repeated many times save more than short ones, because each avoided copy is bigger. For columns near the cutoff, measure.
| Unique ratio | Typical result | Action |
|---|---|---|
| Below 0.05 | Large saving | Convert |
| 0.05 to 0.5 | Moderate saving | Convert, then verify |
| Above 0.5 | Small saving or growth | Usually keep `object` |
| Equal to 1.0 | Always larger | Keep `object` |
Other factors besides memory
Memory is not the only cost. Keep object or string when:
- You apply many string methods. Methods through
.stron a categorical work on the categories, but code that mixes categoricals with new strings often needs extra conversions. - New values arrive often. Assigning a value that is not in the categories raises an error or produces missing data, depending on the operation.
- The column is the key in many merges against plain string columns. Mismatched dtypes can fall back to slower paths.
Conversion can also pay off in speed. Operations such as groupby work on the integer codes, which are faster than comparing strings.
Exercise
A DataFrame has 200,000 rows. Column sku has 190,000 distinct values, and column status has 4 distinct values. Which column should you convert to category, and why?
Show answer
Convert status. Its unique ratio is 0.00002, so four strings are stored once and each row holds a one-byte code. sku has a ratio of 0.95, so the category table would hold nearly as many strings as the original column and the codes would add extra memory, with little or no saving.
Exercise
Write code that prints, for every string column in a DataFrame df, whether converting to category reduces memory.
Show answer
for col in df.selectdtypes(include=["object", "string"]).columns: before = df[col].memoryusage(deep=True) after = df[col].astype("category").memory_usage(deep=True) print(col, after < before)