skip to content

A 50-million-row pandas events DataFrame takes 12 GB in memory; which dtype and read-time changes shrink it, and how do you confirm each one paid off?

level: seniorimportance: should knowfreq 50%

answer

  1. rank columns before changing any
  2. load fewer columns, declare dtypes
  3. smallest integer that holds the range
  4. repeated labels become codes
  5. peak memory, not just the result

basics

~10 s

Rank columns with memory_usage(deep=True), then read only the needed columns with usecols and declared dtypes, downcast numbers with to_numeric(downcast=), and turn repeated labels into category; re-measure after each step and watch the load's peak.

solid answer

~40 s

I start with `df.memory_usage(deep=True).sort_values()` so the effort goes where the bytes are. Then I fix it at the read: `read_csv(usecols=[...], dtype={...})` keeps unused columns out and lets low-cardinality labels arrive as `"category"` and counters as `"int32"`, so the 12 GB version never exists. Numbers already in memory go through `pd.to_numeric(s, downcast="integer"|"unsigned"|"float")`, which picks the smallest dtype that holds the values. Repeated text becomes `category`; in pandas 3.0 the remaining free text infers `str`, which with PyArrow is already far smaller than `object`. After each change I compare the deep total and the process peak, and I check the costs: `float32` keeps about seven significant digits, a narrow integer can overflow in arithmetic, and `category` changes groupby and concat behaviour.

code

python · 20 lines
python
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
n = 200_000
events = pd.DataFrame({
    "event_type": rng.choice(["view", "click", "cart", "buy"], n),
    "session_len": rng.integers(0, 30_000, n),
    "score": rng.random(n),
})
before = events.memory_usage(deep=True)

slim = events.assign(
    event_type=events["event_type"].astype("category"),
    session_len=pd.to_numeric(events["session_len"], downcast="integer"),
    score=pd.to_numeric(events["score"], downcast="float"),
)
after = slim.memory_usage(deep=True)
print(slim.dtypes)
print(pd.DataFrame({"before": before, "after": after}))

go deeper

for a junior

Recall the main levers: read only the columns you need, declare dtypes at the read, use category for repeated labels and smaller numeric dtypes for numbers.

for a middle

Explain how to_numeric picks the smallest dtype, why NaN blocks an integer downcast, and why category helps only when distinct values are few.

for a senior

Show a measured plan: deep ranking, read-time usecols and dtype, one change at a time, peak memory tracked, and a correctness check after each downcast.

for a principal

Weigh standard dtype contracts for shared datasets against per-job tuning, and know when dtype work has run out and chunking or another engine is the real decision.

## Measure first A 12 GB frame of 50 million rows averages about 240 bytes a row, so a handful of columns usually carries most of the weight. Before changing anything, rank them: ```python sizes = df.memory_usage(deep=True).sort_values(ascending=False) print((sizes / 2**20).round(1)) # MiB per column ``` `deep=True` matters: without it, columns of Python objects report only their 8-byte pointers and the ranking is wrong. Keep this Series as the **baseline** for every later step. Put `df.nunique()` beside it: the number of distinct values per column tells you which text columns are candidates for `category` and which are near-unique free text. ## Fix it at the read The cheapest bytes are the ones never loaded. `read_csv` takes two arguments that act before the frame exists: - **`usecols`** reads only the listed columns. A scoring job that needs 9 of 40 columns should never parse the other 31. - **`dtype`** with a dict declares each column's type up front, for example `{"event_type": "category", "user_id": "int32", "amount": "float32"}`. Without it pandas infers `int64`, `float64` and text, and you pay the fat version at peak before shrinking it. Columnar formats give the same lever: `read_parquet(columns=[...])` skips whole columns on disk. Converting after loading still helps the steady state, but the **peak** during the load is set by what the reader produced. ## Shrink the numbers `pd.to_numeric(s, downcast=...)` tries dtypes from smallest to largest and keeps the first that holds every value: | `downcast=` | tries | stops at the first that fits | |---|---|---| | `"integer"` or `"signed"` | int8, int16, int32, int64 | e.g. a 0..30,000 counter becomes `int16` | | `"unsigned"` | uint8 … uint64, only when the minimum is 0 or more | ids that are never negative | | `"float"` | float32, then float64 | values pandas can round-trip within a small tolerance | Three traps: 1. A float column holding **NaN does not become an integer**: the integer downcast requires every value to be present, so the column stays `float64`. 2. **`float32`** keeps roughly seven significant digits. pandas refuses the downcast when the round trip moves a value by more than a small absolute tolerance, but small values still lose their trailing digits. 3. A **narrow integer** stays narrow in arithmetic: two `int16` columns added together give `int16`, and NumPy wraps on overflow without an error. ## Shrink the text Text is usually the biggest column. Two tools, chosen by **cardinality** (the number of distinct values): - **`category`** for repeated labels such as event type, country or device. pandas stores each distinct value once and an integer code per row; with fewer than 127 categories the codes are `int8`, one byte a row. When the distinct values approach the row count, a categorical costs about as much as the plain column, or more. - **The `str` dtype** for free text. In pandas 3.0 text columns infer `str` instead of `object`. With PyArrow installed it stores characters contiguously with 8-byte offsets, far smaller than one Python object per row; without PyArrow it falls back to NumPy object storage and saves nothing. ## Confirm each step paid off Change one thing at a time and keep a record: 1. Re-run `memory_usage(deep=True).sum()` and compare with the baseline. 2. Measure the **process peak**, not just the final frame. `df.astype(...)` on a loaded frame briefly holds old and new columns together, and a merge or groupby afterwards can allocate several times the frame. 3. Re-run the job's tests or a row-count and checksum comparison, because a downcast that changed values is a bug, not a saving. ## What the savings cost | change | cost to check | |---|---| | `int8`/`int16` | overflow in later arithmetic | | `float32` | lost precision in sums and joins on floats | | `category` | categories travel with the column; concatenating frames whose categories differ falls back to a non-categorical dtype, and groupby reports only observed categories by default in 3.0 | | `usecols` | a column dropped at the read must be re-read when a new feature needs it | If, after all of this, the frame still does not fit, the problem is no longer dtypes: chunked processing or a different engine is the next decision. Record the before and after figures for each change, so the next person tuning the job knows which savings were real and which costs were accepted.

  • Why did to_numeric(downcast='integer') leave a float64 column unchanged?
    The column holds NaN. The integer downcast only succeeds when every value is present and survives the cast unchanged, so a column with missing values stays float64. Fill or drop the gaps first, or use the nullable `Int64` dtype, which marks missing values with a mask; pick the representation deliberately rather than expecting downcast to do it.
  • When does converting a text column to category make memory worse?
    When the number of distinct values approaches the number of rows. A categorical stores every distinct value once plus a code per row, so near-unique text such as URLs or user agents pays for all the strings and the codes. Keep such columns as `str`, which with PyArrow is already compact in pandas 3.0, or drop them at the read.
  • Why does the load still hit 12 GB even though the final frame is 3 GB?
    The conversions run after the reader built the full-width frame. `astype` and `to_numeric` create new arrays while the old ones are still alive, so the peak is the fat frame plus the new columns. Moving the decisions into `read_csv(usecols=..., dtype=...)`, or reading Parquet with `columns=`, makes the reader produce the slim frame directly.

  • Convert every text column to category; it always saves memory.
  • Downcasting after the load lowers the peak memory of the load itself.
  • float32 is lossless for any value a float64 column holds.
  • to_numeric(downcast='integer') turns a float column with NaN into int8.
  • Shrinking dtypes never changes results, so no re-test is needed.

Assumes pandas 3.0, where text columns infer the str dtype (PyArrow-backed when installed) instead of object; in 2.x free text loaded as object and converting it was itself a large saving.