Sub topic 4
Measuring memory and performance gains
This chapter assumes you can create Series and DataFrames, read dtype output such as int64 and object, and use groupby and value_counts. It also assumes you have seen astype("category"). The goal here is to measure what a categorical column saves you on your own data, so you can decide whether to convert.
Where the savings come from
An object column holds one pointer per row, and each pointer refers to a separate Python string. A categorical column holds:
- One small integer code per row.
- One copy of each distinct value, stored in the categories index.
The memory cost of a categorical is therefore roughly rows × code size + distinct values × value size. The cost of an object column is roughly rows × (pointer size + string size). The gap grows as rows increase and distinct values stay few.
pandas picks the smallest signed integer type that can address all categories:
| Number of categories | Code dtype | Bytes per row |
|---|---|---|
| up to 127 | `int8` | 1 |
| up to 32,767 | `int16` | 2 |
| more than 32,767 | `int32` | 4 |
Beyond about 2.1 billion categories, codes would need int64. You will not meet that in practice.
Measuring memory correctly
Use memory_usage(deep=True). Without deep=True, pandas counts only the 8-byte pointers of an object column and ignores the strings they point to. The comparison then understates the object column badly.
import pandas as pd
n = 300_000
s_obj = pd.Series(["red", "green", "blue"] * (n // 3))
s_cat = s_obj.astype("category")
shallow = s_obj.memory_usage()
deep_obj = s_obj.memory_usage(deep=True)
deep_cat = s_cat.memory_usage(deep=True)
print("object, shallow:", shallow)
print("object, deep: ", deep_obj)
print("category, deep: ", deep_cat)
print("codes dtype: ", s_cat.cat.codes.dtype)
print("ratio: ", round(deep_obj / deep_cat, 1))On a typical 64-bit build, the object column reports about 18 MB with deep=True and the categorical about 0.3 MB. The exact numbers depend on your pandas and Python versions.
You can break the categorical figure into its two parts:
import pandas as pd
s_cat = pd.Series(["red", "green", "blue"] * 100_000).astype("category")
print("codes: ", s_cat.cat.codes.memory_usage(deep=True))
print("categories:", s_cat.cat.categories.memory_usage(deep=True))
print("total: ", s_cat.memory_usage(deep=True))The codes part grows with the number of rows. The categories part grows with the number of distinct values. This split explains every result in the rest of the chapter.
The effect of cardinality
Cardinality is the number of distinct values in a column. A categorical wins when cardinality is low relative to the row count. The next script varies cardinality while holding the row count fixed.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 200_000
def memory_pair(n_unique):
pool = np.array([f"item-{i:06d}" for i in range(n_unique)], dtype=object)
s_obj = pd.Series(pool[rng.integers(0, n_unique, n)], dtype=object)
s_cat = s_obj.astype("category")
return s_obj.memory_usage(deep=True), s_cat.memory_usage(deep=True)
print(f"{'unique':>8} {'object':>12} {'category':>12} {'ratio':>6}")
for k in [3, 100, 5_000, 200_000]:
obj_bytes, cat_bytes = memory_pair(k)
print(f"{k:>8} {obj_bytes:>12,} {cat_bytes:>12,} {obj_bytes / cat_bytes:>6.1f}")Expect a large ratio at 3 and 100 values, a smaller one at 5,000, and a ratio near 1 at 200,000. In the last case almost every row has its own value. The categories index then stores nearly as many strings as the object column did, and you pay for the code array on top.
A practical rule is to try a conversion when distinct values are below about half the number of rows, and to be confident when they are below a few percent. Check cardinality before converting:
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Oslo", "Pune", "Lima", "Oslo"],
"id": ["a1", "b2", "c3", "d4", "e5", "f6"],
})
print((df.nunique() / len(df)).round(2))A column with a ratio near 1.0 is a poor candidate. id above is one such column.
Measuring speed
Memory is the reliable gain. Speed gains depend on the operation and are often modest, so measure them. Operations that work on the integer codes instead of the strings benefit most:
groupbyon the column, because grouping uses codes directly.value_counts, because counting uses a bincount over codes.- Equality comparison with a scalar, because pandas compares one category and then the codes.
sort_values, because it sorts integers rather than strings. For an unordered categorical, the sort follows category order, which is lexical for categories created byastype("category").
This script times three operations on both representations. It reports the best of several runs, which is less noisy than a single run.
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 2_000_000
pool = np.array(["north", "south", "east", "west", "central"], dtype=object)
df_obj = pd.DataFrame({
"region": pool[rng.integers(0, len(pool), n)],
"sales": rng.random(n),
})
df_obj["region"] = df_obj["region"].astype(object)
df_cat = df_obj.assign(region=df_obj["region"].astype("category"))
def best_of(func, repeats=5):
times = []
for _ in range(repeats):
start = time.perf_counter()
func()
times.append(time.perf_counter() - start)
return min(times)
tests = {
"groupby sum": lambda d: d.groupby("region", observed=True)["sales"].sum(),
"value_counts": lambda d: d["region"].value_counts(),
"equals 'east'": lambda d: d["region"] == "east",
}
print(f"{'operation':<14} {'object (s)':>11} {'category (s)':>13} {'speedup':>8}")
for name, op in tests.items():
t_obj = best_of(lambda: op(df_obj))
t_cat = best_of(lambda: op(df_cat))
print(f"{name:<14} {t_obj:>11.4f} {t_cat:>13.4f} {t_obj / t_cat:>7.1f}x")The observed=True argument keeps the groupby free of version-dependent warnings. The next chapters cover what it does. Results vary by machine, pandas version, and string dtype, so run the script on your own setup before drawing conclusions.
Costs that offset the gains
Conversion is not free, and some operations get slower on a categorical.
- Conversion time.
astype("category")must factorize the whole column, which means finding the distinct values and assigning codes. It takes about as long as agroupbyon the column. If you convert and then use the column once, you may lose time overall. - Peak memory during conversion. The original object column and the new categorical exist together until you drop the original. Convert one column at a time on large frames, and assign back to the same name so the old column is released.
- String methods.
.strmethods on a categorical run on the categories and then map results back through the codes. This is fast for few categories. It is no faster than before for a column with a million categories. - Arithmetic. You cannot add or multiply a categorical column, even if its categories are numbers. Aggregations such as
sumraise errors. Keep numeric data in numeric dtypes. - Repeated modification. Assigning a value that is not already a category fails or forces a dtype change. Heavy edit workloads fit categoricals poorly. The chapter on managing categories explains the rules.
A repeatable workflow
- Measure the current footprint with
df.memory_usage(deep=True)and look for the largest object columns. - Check cardinality with
df.nunique() / len(df)for those columns. - Convert the low-cardinality candidates, one column at a time.
- Re-measure with
deep=Trueand confirm the saving. - Time the operations your code actually runs, on both versions, and keep the categorical only where it helps or where memory pressure matters.
This function wraps steps 1 to 3 and reports each saving:
import pandas as pd
def shrink_categoricals(df, max_ratio=0.5):
out = df.copy()
for col in out.select_dtypes(include="object").columns:
if out[col].nunique() / len(out) < max_ratio:
before = out[col].memory_usage(deep=True)
out[col] = out[col].astype("category")
after = out[col].memory_usage(deep=True)
print(f"{col}: {before:,} -> {after:,} bytes")
return out
df = pd.DataFrame({
"status": ["open", "closed", "open", "open"] * 1000,
"note": [f"text {i}" for i in range(4000)],
})
slim = shrink_categoricals(df)
print(slim.dtypes)Only status converts. note has a distinct value on every row, so it stays object.
Exercise
Exercise
A DataFrame has 1,000,000 rows. Column A holds 12 distinct country names. Column B holds a distinct order reference on every row. You call astype("category") on both and compare memory_usage(deep=True) before and after. What do you expect for each column, and which code dtype does A's categorical use?
Show answer
Column A shrinks sharply. Each row costs one byte for an int8 code (12 categories is below 128), and the 12 names are stored once. Column B shows little or no saving, and it can even grow. It has 1,000,000 categories, so the codes are int32 (4 bytes per row) and the categories index still stores every string. B should stay object or use a string dtype.