Sub topic 6
Converting repetitive strings to category
This chapter assumes you can build a DataFrame, read dtypes, and use memory_usage(deep=True) from the earlier chapters. It covers the category dtype, which is the main way to shrink columns of repeated strings.
The problem with repeated strings
An object column stores one Python string reference per row. If a column holds the same five country codes across 100,000 rows, pandas still keeps 100,000 references. A deep memory count also sees the string objects behind them.
The category dtype stores each distinct value once. Each row then holds a small integer code that points to that value.
Converting a column
Build the sample data from the first chapter, then convert the country column:
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 100_000
df = pd.DataFrame({
"user_id": rng.integers(0, 50_000, n),
"age": rng.integers(18, 90, n),
"score": rng.random(n),
"country": rng.choice(["US", "DE", "FR", "JP", "BR"], n),
})
print(df["country"].memory_usage(deep=True))
df["country"] = df["country"].astype("category")
print(df["country"].dtype)
print(df["country"].cat.categories)
print(df["country"].cat.codes.dtype)
print(df["country"].memory_usage(deep=True))Compare the two memory numbers. The category version is a small fraction of the object version. The exact figures depend on your pandas version and platform.
The cat.codes dtype is int8. pandas picks the smallest integer type that can index all the categories, so five categories need one byte per row. The savings come from that one byte per row plus a tiny table of five strings.
When category pays off
The saving depends on cardinality, the number of distinct values compared with the number of rows.
| Column | Distinct values | Rows | Category helps? |
|---|---|---|---|
| Country code | 5 | 100,000 | Yes, large saving |
| Product type | 200 | 100,000 | Yes |
| Email address | about 99,000 | 100,000 | No |
| Unique ID string | 100,000 | 100,000 | No, it can use more memory |
If almost every value is unique, the categories table holds nearly every string anyway, and the codes are extra. A practical rule is to convert when the unique values are well below half of the rows. The shrink helper in a later chapter uses 50% as its default threshold. You can check with df[col].nunique() / len(df).
Setting category at load time
If you already know a column is repetitive, ask for the dtype when reading the file. The large object column is then never built.
from io import StringIO
csv = StringIO("age,country\n34,US\n29,DE\n41,US\n")
small = pd.read_csv(csv, dtype={"age": "int8", "country": "category"})
print(small.dtypes)Quick checks after converting
A categorical column behaves like a string column for most reads, but a few things differ. The next chapters cover these in detail, so here is a short preview:
- Assigning a value that is not in the categories raises an error or produces
NaN, depending on the operation. - Grouping on a category column includes unused categories unless you pass
observed=True. - Comparing two categorical columns requires that they have the same categories.
means = df.groupby("country", observed=True)["score"].mean()
print(means)Summary of the method
- Check the cardinality with
nunique(). - Convert with
astype("category"), or setdtypeinread_csv. - Confirm the saving with
memory_usage(deep=True).
Exercise
A DataFrame has 1,000,000 rows. Column city has 300 distinct values. Column order_id is a string with 1,000,000 distinct values. Which column should you convert to category, and why? What dtype will the integer codes of the converted column use?
Show answer
Convert city. It has few distinct values compared with the row count, so storing each name once and keeping a small code per row saves memory. order_id is unique on every row, so a category would store every string plus a code per row and would not save memory. With 300 categories the codes need more than 127 values, so pandas uses int16.
Exercise
Write code that reads a CSV file sales.csv with columns qty (values 1 to 100) and region (about 8 distinct strings), creating compact columns directly.
Show answer
sales = pd.read_csv("sales.csv", dtype={"qty": "int8", "region": "category"})