Skip to content

Lesson 7 of 9 · 23m

Shrinking Memory Before You Buy a Bigger Box

How pandas actually uses memory, dtype downgrades, categoricals, column pruning, sparse data, and measuring before optimizing.

pandas memory problems rarely arrive as an out-of-memory error first. They arrive as a worker node swapping, a Kubernetes pod getting OOMKilled during month-end, or a notebook that takes eleven minutes because every operation copies a 12 GB frame. The first discipline is measurement; the second is understanding where the bytes live.

Measure the real footprint

df.memory_usage(deep=True).sort_values(ascending=False)
df.info(memory_usage="deep")

Without deep=True, object columns report only pointer size, not the strings or Python objects they point at. A column can look like 8 MB and actually be 800 MB. Measure by column because optimization is almost never uniform: three columns usually dominate the footprint.

The first win is dropping columns and rows early

The cheapest byte is the one never loaded. Read only what the pipeline needs:

cols = ["event_id", "customer_id", "created_at", "amount", "country"]
df = pd.read_csv("events.csv", usecols=cols, parse_dates=["created_at"])

Filter earlier if the source supports it. pandas cannot predicate-push into a CSV, but it can into Parquet when using the right engine arguments. Wide operational dumps are convenient for exploration and terrible for production.

Downcast numerics deliberately

df["amount"] = pd.to_numeric(df["amount"], downcast="float")
df["quantity"] = pd.to_numeric(df["quantity"], downcast="integer")

float64 to float32 halves memory but reduces precision. int64 to int16 only works if values fit. Check ranges before downcasting, especially identifiers and monetary amounts. Never turn an ID into a smaller integer just because today's range fits — IDs grow.

category and string dtypes are different tools

df["country"] = df["country"].astype("category")
df["customer_id"] = df["customer_id"].astype("string")

Low-cardinality repeated strings compress beautifully as categories. High-cardinality strings do not — the dictionary dominates and lookup can become slower. IDs usually belong in string or binary/hash form, not category. Measure cardinality:

df["country"].nunique(), len(df)

Copies are hidden memory

Filtering, sorting, concatenating, merging, and many transformations allocate. Peak memory is often two or three times the final frame size. That is why "the final dataframe is only 2 GB" does not explain an 8 GB OOM. Restructure the pipeline to process chunks, project columns early, or use a tool with streaming execution.

Field notes

  • memory_usage(deep=True) is mandatory for object-heavy data.
  • Optimize the largest columns first; dtype micro-tuning everything wastes time.
  • Downcasting is a correctness decision, not just compression.
  • Peak memory matters more than final memory during merges and sorts.
  • Parquet plus column projection is often a bigger win than any in-memory trick.

Was this lesson helpful?

Sign in to rate