Sub topic 1
Reducing DataFrame Memory with Downcasting and Categories
Prerequisites
Assume you know basic Python, NumPy arrays, pandas DataFrames, indexing, and common pandas dtypes such as int64, float64, and object.
Measuring memory: `memory_usage(deep=True)` and `info()`
A DataFrame's default dtypes often use more memory than its values require. Measure before optimizing so you can verify the result.
info(memory_usage="deep") gives a readable summary. memory_usage(deep=True) gives per-column counts, including the Python objects referenced by an object column.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame({
"user_id": rng.integers(0, 50_000, 100_000),
"age": rng.integers(18, 90, 100_000),
"country": rng.choice(["US", "DE", "FR", "JP", "BR"], 100_000),
})
df.info(memory_usage="deep")
usage = df.memory_usage(deep=True)
print(usage)
print(f"Total: {usage.sum() / 1024**2:.2f} MiB")The index appears as a separate row. The deep=True option matters because shallow measurement counts references in an object column, but deep measurement also counts the referenced strings.
Dtype sizes and value ranges
Fixed-width numeric dtypes reserve the same number of bytes for each value. Smaller types have narrower ranges.
| Dtype | Bytes per value | Typical range |
|---|---|---|
| `int8` | 1 | -128 to 127 |
| `int16` | 2 | -32,768 to 32,767 |
| `int64` | 8 | About -9.2 quintillion to 9.2 quintillion |
| `float32` | 4 | About 7 decimal digits of precision |
| `float64` | 8 | About 15 decimal digits of precision |
Choose a dtype from the column's minimum and maximum, not from its current appearance.
Downcasting integers with `pd.to_numeric`
Downcasting selects a smaller dtype that can safely hold the values.
before = df.memory_usage(deep=True).sum()
df["age"] = pd.to_numeric(df["age"], downcast="integer")
df["user_id"] = pd.to_numeric(df["user_id"], downcast="unsigned")
print(df[["age", "user_id"]].dtypes)
print(f"Saved: {(before - df.memory_usage(deep=True).sum()) / 1024**2:.2f} MiB")downcast="unsigned" is appropriate only when values are never negative. Check ranges and preserve missing-value behavior before applying a narrower dtype.
Exercise
Why should you use memoryusage(deep=True) instead of only checking df.memoryusage() for string columns?
Show answer
Deep measurement includes the memory occupied by the Python string objects referenced by object columns.