Sub topic 4
Measuring memory and performance gains
This chapter assumes you know how to create a categorical column with astype("category"), and that you know what object and int64 dtypes are. Here you will measure what a categorical saves, find the point where it stops helping, and time an operation yourself.
Where the savings come from
An object column stores one Python string reference per row, and each string is a separate object in memory. A categorical stores each distinct value once, in the categories. Each row then holds only a small integer code.
The saving therefore depends on how many rows share each distinct value. Many repeats give a large saving. Few repeats give little or none.
Measuring memory
Use memory_usage(deep=True). Without deep=True, pandas counts only the pointers in an object column and ignores the strings they point to, so the object column looks much smaller than it is.
import pandas as pd
n = 300_000
s_obj = pd.Series(["red", "green", "blue"] * (n // 3))
s_cat = s_obj.astype("category")
print(s_obj.memory_usage(deep=True))
print(s_cat.memory_usage(deep=True))
print(s_cat.cat.codes.dtype)The exact numbers vary by platform and pandas version. The object column takes megabytes, and the categorical takes a few hundred kilobytes. With three categories, pandas picks the int8 dtype for the codes, so each row costs one byte. Pandas chooses the smallest integer type that can hold the number of categories.
When categoricals do not help
If almost every value is unique, the categorical stores the full list of strings in its categories and also adds a code for every row. It can end up larger than the object column.
import pandas as pd
n = 300_000
ids = pd.Series([f"id_{i}" for i in range(n)])
print(ids.memory_usage(deep=True))
print(ids.astype("category").memory_usage(deep=True))A rough rule is to try a categorical when the number of distinct values is well below half the number of rows. Always measure, because string length also matters.
| Column shape | Typical result |
|---|---|
| Few distinct values, many rows | Large memory saving |
| Many distinct values, mostly unique | Little saving, sometimes larger |
| Short strings, few rows | Difference too small to matter |
Measuring speed
A categorical column can speed up grouping, because pandas works on integer codes instead of hashing strings. Time your own data, since results depend on its size and shape.
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 2_000_000
labels = rng.choice(["north", "south", "east", "west"], size=n)
df_obj = pd.DataFrame({"region": labels, "value": rng.random(n)})
df_cat = df_obj.assign(region=df_obj["region"].astype("category"))
def best_time(func, repeats=5):
times = []
for _ in range(repeats):
start = time.perf_counter()
func()
times.append(time.perf_counter() - start)
return min(times)
t_obj = best_time(lambda: df_obj.groupby("region")["value"].sum())
t_cat = best_time(lambda: df_cat.groupby("region", observed=True)["value"].sum())
print(f"object: {t_obj:.4f} s")
print(f"categorical: {t_cat:.4f} s")The code takes the best of several runs to reduce noise from other processes. It passes observed=True explicitly so the grouping behaves the same on every pandas version. A later chapter explains that setting.
Speed gains are not guaranteed. The conversion itself costs time, so converting once and reusing the column pays off, while converting before every operation does not. Operations that need the actual strings, such as .str methods, work on the categories and then map the results back. They are not always faster.
A repeatable workflow
- Check cardinality with
df[col].nunique()againstlen(df). - Convert a copy of the column and compare
memory_usage(deep=True)before and after. - Time the operation you actually run, on realistic data.
- Keep the categorical only if the gain is worth the extra care it needs.
Exercise
A column of 1,000,000 customer email addresses, almost all unique, is converted with astype("category"). Memory use goes up. Why, and what would you check first before converting a column?
Show answer
The categorical must store every distinct email once in its categories and also keep an integer code for each row, so it holds the strings plus the codes. The object column holds only the strings. Before converting, compare nunique() with the number of rows, and then confirm with memory_usage(deep=True) on a converted copy.