Sub topic 3
Under the Hood: Categories and Integer Codes
Assume you know how to create and index pandas DataFrames and recognize common dtypes such as int64, float64, and object.
Categories store labels once
A categorical column separates its data into:
categories: the distinct labels, stored once.codes: one integer per row that points to a category.
Missing values use code -1.
import pandas as pd
df = pd.DataFrame({"country": ["US", "DE", "US", None]})
df["country"] = df["country"].astype("category")
print(df["country"].cat.categories.tolist())
print(df["country"].cat.codes.tolist())The codes might be [1, 0, 1, -1]. The exact category order can vary.
Pitfalls with categorical columns
A category has a fixed set of allowed labels. Assigning a new label directly fails unless you add it first.
df["country"] = df["country"].cat.add_categories(["JP"])
df.loc[3, "country"] = "JP"Grouping can also include unused categories. Use observed=True when you only want groups present in the data:
print(df.groupby("country", observed=True).size())Categories are useful for repeated labels. They can waste memory when most values are unique. They can also complicate comparisons with ordinary strings or combining DataFrames whose category sets differ.
Check values after shrinking
Downcasting changes storage, so verify values immediately. Integer values should match exactly. Floating-point values may differ slightly because float32 has less precision.
import numpy as np
before = pd.Series([10, 20, 30], dtype="int64")
after = pd.to_numeric(before, downcast="integer")
assert (before == after).all()
floats = pd.Series([0.1, 0.2, 0.3])
small_floats = pd.to_numeric(floats, downcast="float")
assert np.allclose(floats, small_floats, rtol=1e-6, equal_nan=True)Choose dtypes while loading
Set dtype in read_csv so pandas does not first create oversized columns. Use usecols to avoid loading columns you do not need.
from io import StringIO
csv = StringIO("user_id,age,country,unused\n4,34,US,x\n7,29,DE,y\n")
df = pd.read_csv(
csv,
usecols=["user_id", "age", "country"],
dtype={"user_id": "uint8", "age": "int8", "country": "category"},
)
print(df.dtypes)Build a reusable shrink function
Apply numeric downcasting and convert low-cardinality text columns. Keep the original DataFrame for validation.
def shrink(df, max_unique_ratio=0.5):
out = df.copy()
for col in out.select_dtypes(include="integer"):
out[col] = pd.to_numeric(out[col], downcast="integer")
for col in out.select_dtypes(include="floating"):
out[col] = pd.to_numeric(out[col], downcast="float")
for col in out.select_dtypes(include=["object", "string"]):
if len(out) and out[col].nunique() < max_unique_ratio * len(out):
out[col] = out[col].astype("category")
return outExercise
Why does a categorical column use integer codes instead of storing every string separately?
Show answer
It stores each distinct label once and stores a compact integer code for each row.