Connect any database. Ask in plain English.

Try free
← Blog

Pandas Out of Memory: Measure the DataFrame, Then Cut It From 808 MB to 181 MB (2026)

We loaded 5 million invented orders into pandas 3.1.2 and measured each fix: categories, parsed dates and smaller numbers took the DataFrame from 808 MB to 181 MB, and setting the types while reading kept the peak at 378 MB instead of 1,666 MB. Plus the operations that multiply memory (a merge on a repeated key tripled the rows, apply(axis=1) added 516 MB) and what to use when the data still doesn't fit.

Fastero Dev TeamFastero Dev Team2026-12-02

For this guide we generated a CSV of 5 million invented orders (13 columns, 534 MB), loaded it with pandas 3.1.2, and measured every column with memory_usage(deep=True) and the Python process itself with psutil. Then we ran the merges, pivots, copies and apply calls that usually push a notebook over the edge, each in a fresh process on one Windows laptop, with a watchdog that stopped any test before it reached 3 GB.

The short answer: pandas runs out of memory when a DataFrame, or a temporary copy an operation makes, needs more RAM than the machine has. Measure first with df.info(memory_usage="deep"), then fix in this order: drop columns you don't use, turn repeated text into category, parse dates, downcast integers, and set those types when you read the file rather than afterwards. On our 5-million-row file that took the DataFrame from 808 MB to 181 MB, and reading with the types set peaked at 378 MB instead of 1,666 MB. Then avoid the operations that multiply memory: merges on repeated keys, wide pivots and apply(axis=1). Checked 2 December 2026.

Fastero

Connect your database. Ask questions. Get dashboards.

Postgres, BigQuery, Snowflake, and 10+ sources — live-connected, AI-powered, no dashboard builder learning curve.

Try free →

Why pandas runs out of memory

pandas keeps the whole DataFrame in RAM, and many operations build a new one before the old one can be freed. The pandas docs put it plainly: "Even datasets that are a sizable fraction of memory become unwieldy, as some pandas operations need to make intermediate copies."

It shows up in one of three ways:

  • MemoryError: Unable to allocate ... when NumPy asks for a block the system can't give. Our general guide to Python MemoryError covers the error itself.
  • The Jupyter kernel dies with no Python error at all, because the operating system ended the process. See Jupyter kernel died.
  • The machine starts swapping, and a cell that took seconds takes minutes.

This pivot asks for a table with one row per order and one column per customer:

df.pivot_table(index="order_id", columns="customer_id", values="revenue", aggfunc="sum")
MemoryError: Unable to allocate 1.82 TiB for an array with shape (1999995000000,) and data type bool

It failed in 0.8 seconds, before using the memory, because the request was impossible. One that is only slightly too big is worse: it succeeds, fills the RAM, and the kernel dies later.

How much memory does a pandas DataFrame use?

Ask pandas, with deep so text is measured too:

import pandas as pd
 
df = pd.read_csv("orders.csv")
df.info(memory_usage="deep")
<class 'pandas.DataFrame'>
RangeIndex: 5000000 entries, 0 to 4999999
Data columns (total 13 columns):
 #   Column       Dtype
---  ------       -----
 0   order_id     int64
 1   order_ref    str
 2   order_date   str
 3   customer_id  int64
 4   region       str
 5   country      str
 6   channel      str
 7   product      str
 8   status       str
 9   quantity     int64
 10  unit_price   float64
 11  discount     float64
 12  revenue      float64
dtypes: float64(3), int64(3), str(7)
memory usage: 807.5 MB

df.memory_usage(deep=True) gives the same per column, in bytes. Without deep, pandas 2.x-style object columns are counted as pointers only: our object version of this file printed memory usage: 495.9+ MB, and the docs explain the plus sign: "The + symbol indicates that the true memory usage could be higher, because pandas does not count the memory used by values in columns with dtype=object."

What each kind of column costs, in bytes per row, on these 5 million rows:

What the column holds object, as deep=True counts it object, each string counted once str (pyarrow) category
A unique 14-character ID 63.0 63.0 22.0 26.1
A date as text (730 dates) 59.0 8.6 18.0 2.0
60 product names 61.8 8.0 20.8 1.0
4 region names 53.5 8.0 12.5 1.0

An int64 or float64 column costs 8 bytes a row, int8 1 byte, and a date parsed to datetime64 8 bytes.

Object strings, pyarrow strings and why deep=True can overcount

In pandas 2.x, text is stored as object: every row holds an 8-byte pointer to a Python string. In our test the CSV reader reused string objects for repeated values (5 million region values were 528 distinct Python objects), so a repeated value really cost about 8 bytes a row. deep=True sizes every row's string as if it were its own, so it reported 2,176 MB for a DataFrame that held about 764 MB; the process grew by 812 MB.

That sharing doesn't survive a transformation. One .str.upper() on the five repeated-text columns made 5 million new strings in each and took the process from 812 MB to 2,162 MB. On pyarrow strings, the same step left it at 848 MB.

pandas 3.0 made a dedicated str type the default, "backed by PyArrow under the hood, if installed, otherwise falling back to being backed by NumPy object-dtype". pyarrow is not a required dependency: pip install pandas brought in only NumPy, python-dateutil and tzdata. Read with the Python-object storage pandas falls back to, our file measured exactly what it did as object. If you're on pandas 3, run pip install pyarrow.

How to reduce pandas memory usage, in the order to try

Horizontal bars of one 5-million-row DataFrame after each fix: text as object 764 MB really used though memory_usage(deep=True) reports 2,176 MB, text as pyarrow-backed str 808 MB, repeated text as category with dates parsed 396 MB, smaller numbers 286 MB, unused ID column dropped 181 MB

The same 5-million-row DataFrame after each fix, measured with memory_usage(deep=True) in pandas 3.1.2; the object bar counts each distinct string once. Invented data.

1. Drop the columns you don't use

The unique order reference was 105 MB of our 286 MB after the other fixes, and the analysis never used it. Pass usecols to read_csv, or columns= to read_parquet, so it's never read; our guide to reading a large CSV in pandas times both.

2. Turn repeated text into category

for col in ["region", "country", "channel", "product", "status"]:
    df[col] = df[col].astype("category")

A category column stores each distinct value once and a small integer code per row: these five columns went from 388 MB to 24 MB. It pays only when values repeat. The docs warn that "If the number of categories approaches the length of the data, the Categorical will use nearly the same or more memory than an equivalent object dtype representation", and the unique order reference grew from 105 MB as str to 125 MB as category.

3. Parse dates

pd.to_datetime(df["order_date"]) turned 86 MB of date text into 38 MB of datetime64, and date arithmetic works on it.

4. Downcast numbers

for col in ["order_id", "customer_id", "quantity"]:
    df[col] = pd.to_numeric(df[col], downcast="integer")
for col in ["unit_price", "discount"]:
    df[col] = pd.to_numeric(df[col], downcast="float")

downcast="integer" picks the smallest integer type that holds today's values: int32 for both IDs and int8 for quantity. With the floats as float32, the DataFrame went from 396 MB to 286 MB. A later file with bigger IDs needs a bigger type, and float32 keeps about seven significant digits, so we kept revenue as float64: summed in float32, the 5 million revenues came to 4,014,742,272.00 instead of 4,014,742,350.28.

5. Set the types while reading, not afterwards

Converting after the load holds the big version and the small one at once. This read gives the same 181 MB DataFrame directly:

low = ["region", "country", "channel", "product", "status"]
df = pd.read_csv(
    "orders.csv",
    usecols=lambda c: c != "order_ref",
    parse_dates=["order_date"],
    dtype={**{c: "category" for c in low}, "order_id": "int32", "customer_id": "int32",
           "quantity": "int8", "unit_price": "float32", "discount": "float32"},
)
Same 181 MB DataFrame Process peak Process held after
Read with defaults, then convert 1,666 MB 422 MB
Read with the types set 378 MB 275 MB

Both include the 89 MB that Python, pandas and pyarrow use before reading.

Connect any database. Ask in plain English.

Start free →

Which pandas operations multiply memory?

Each row started from the 181 MB DataFrame in a fresh process; the peak is how far the process grew during that step:

Operation Result Peak above the start Time
merge on a unique key 5.0 million rows, 196 MB +159 MB 2.7 s
merge on a key repeated 1 to 5 times 15.0 million rows, 587 MB +831 MB 3.0 s
pivot_table, customers by products 400,000 by 60, 185 MB, 81% empty +426 MB 4.5 s
groupby on the same two keys 4.5 million rows, 58 MB +426 MB 1.9 s
df.copy() 181 MB +241 MB 0.05 s
A filter keeping 85% of rows 4.25 million rows, 187 MB +214 MB 0.2 s
df.rename(columns=str.upper) shares the data +0.4 MB 0.001 s
to_numpy() on 1 million rows one object array +396 MB 2.9 s
apply(axis=1) on 1 million rows 1 million numbers +516 MB 22.3 s
The same sum, vectorized 1 million numbers +3.9 MB 0.005 s

Merges on a repeated key

The customer table here was an address history, with each customer on 1 to 5 rows. Merged on customer_id, every order matched every row of its customer, and 5 million orders became 15 million rows. The pandas docs warn: "Merging on duplicate keys significantly increase the dimensions of the result and can cause a memory overflow." validate turns the surprise into an error before the merge runs:

orders.merge(history, on="customer_id", how="left", validate="many_to_one")
pandas.errors.MergeError: Merge keys are not unique in right dataset; not a many-to-one merge
 
Duplicates in right:
  customer_id
           1
           1
           1
           2
           2 ...

It raised in 0.8 seconds. Deduplicate the right table first, for example with drop_duplicates("customer_id", keep="last"), or aggregate it to one row per key. Pandas merge walks through the other ways a merge multiplies rows.

Pivots and unstack

A pivot makes one cell for every pair of row and column labels, whether or not any data falls in it. Count the cells before you run it:

for col in ["product", "order_date"]:
    cells = df["customer_id"].nunique() * df[col].nunique()
    print(f"customer_id x {col}: {cells:,} cells, {cells * 8 / 2**30:.2f} GiB as float64")
customer_id x product: 23,999,940 cells, 0.18 GiB as float64
customer_id x order_date: 291,999,270 cells, 2.18 GiB as float64

The first pivot came out 81% empty; the second would need 2.18 GiB, so we didn't run it. When you only need the numbers, keep them long with groupby, which held the same totals in 58 MB. Pandas pivot table has the reshaping options.

Copies

pandas 3 made copy-on-write the default: methods return results that behave as copies, but the release notes say "under the hood pandas will use views as much as possible, and only copy when needed". Our rename cost 0.4 MB, and changing one column of the renamed frame afterwards copied only that column (38 MB). Real copies are still easy to make:

  • Filters copy the rows they keep, plus an index of the original row labels: 32 MB of our 187 MB result. reset_index(drop=True) drops it.
  • to_numpy() on mixed column types builds one object array with a Python object per value: 36 MB of DataFrame became 381 MB.
  • Old variables keep their DataFrames alive. In a notebook, df_raw, df_clean and df_final all stay in memory until you del them; Jupyter notebook memory usage covers finding and freeing them.

apply(axis=1)

apply with axis=1 builds a Series for every row and calls Python on it. On 1 million rows it took 22.3 seconds and pushed the process up 516 MB; the same arithmetic on whole columns took 0.005 seconds and 3.9 MB:

slow = df.apply(lambda r: r["unit_price"] * r["quantity"] * (1 - r["discount"]), axis=1)
fast = df["unit_price"] * df["quantity"] * (1 - df["discount"])

Process the file in pieces

When the answer is a summary, the whole file never has to be in memory at once. read_csv(..., chunksize=1_000_000) returns the file a million rows at a time, and you keep a running total; on this file that peaked at 134 MB. The pandas docs add that "Chunking works well when the operation you’re performing requires zero or minimal coordination between chunks", which rules out joins and sorts across the whole file. The code and timings are in pandas read large CSV.

When the data simply doesn't fit: DuckDB, Polars or more memory

For work that needs the whole dataset, use an engine that streams it. We ran the repeated-key merge as one job: 5 million orders joined to the 1.2-million-row history, then revenue totalled by segment and signup year (27 rows). Median of three runs, whole job, reading included:

Tool Process peak Seconds
pandas, with usecols and dtype 1,373 MB 9.2
DuckDB 2.0.1, defaults 746 MB 1.2
DuckDB, memory_limit = '500MB' 573 MB 1.5
DuckDB, '200MB' and 2 threads 316 MB 5.1
Polars 2.2.0, streaming engine 801 MB 0.7

All five returned the same total. DuckDB's docs describe "a state of the art out-of-core query engine that can spill to disk for larger-than-memory processing": with 200 MB and two threads it wrote temporary files during the query and finished. With 200 MB and its default of 16 threads on this laptop, it stopped instead:

_duckdb.OutOfMemoryException: Out of Memory Error: could not allocate block of size 256.0 KiB (190.5 MiB/190.7 MiB used)
 
Possible solutions:
* Reducing the number of threads (SET threads=X)
* Disabling insertion-order preservation (SET preserve_insertion_order=false)
* Increasing the memory limit (SET memory_limit='...GB')

The DuckDB version, with the result handed back to pandas:

import duckdb
 
con = duckdb.connect()
con.execute("SET memory_limit = '500MB'")
by_segment = con.sql("""
    SELECT h.segment, h.signup_year, sum(o.revenue) AS revenue
    FROM read_csv('orders.csv') AS o
    JOIN 'history.parquet' AS h USING (customer_id)
    GROUP BY ALL ORDER BY ALL
""").df()

And Polars, whose streaming engine, its docs say, runs the query "in batches allowing you to process datasets that do not fit in memory":

import polars as pl
 
by_segment = (pl.scan_csv("orders.csv").select("customer_id", "revenue")
                .join(pl.scan_parquet("history.parquet"), on="customer_id")
                .group_by("segment", "signup_year").agg(pl.col("revenue").sum())
                .collect(engine="streaming"))

pandas builds the whole 15-million-row merge before it can total it; DuckDB and Polars run the join and the totals as one query and read only the columns it names. More in DuckDB in Python and Polars vs pandas.

The third answer is more RAM. As a guide from this file: holding the data took 181 to 808 MB depending on the types, and reading it with defaults peaked at 1.7 GB. How much RAM for data science sizes a machine from your own numbers.

When the notebook needs a bigger machine for an hour

Fastero is an AI and data platform where people and AI agents work together on a team's data. Its notebooks are standard .ipynb files with pandas installed; for memory, the machine is what matters:

  • Standard is 1 CPU and 2 GB for a notebook server, included on every plan. Our 5-million-row DataFrame fits on it after the fixes above (181 MB, peaking at 378 MB while reading). With default types it's 808 MB, and a one-thread read like a 1-CPU machine's peaked at 995 MB, which leaves little room for anything else. Fix the types first: it's free and often enough.
  • On Pro, a notebook can move to a bigger machine for the job that really needs it: Medium is 2 CPUs and 8 GB at $0.20 an hour, Large 4 CPUs and 16 GB at $0.40, Extra large 8 CPUs and 32 GB at $0.80. It's charged by the second from money you add to the balance (Pro's $20 per editor a month doesn't include it), so a one-off big load on 16 GB costs cents, not a new laptop.
  • SQL cells push the heavy part to the database. A SQL cell runs on a saved Postgres, MySQL, SQL Server, Redshift, Oracle or BigQuery connection and lands in Python as a DataFrame named after the cell, so a join or a GROUP BY can return 27 rows instead of 15 million.
  • Schedules run on the server on a cron expression, with no browser open. The Free plan includes 6 hours a day of notebook and Python time; see pricing.

A Fastero notebook titled Solar output against forecast, with a pandas cell that builds a DataFrame of twelve invented solar sites and prints them sorted by output against forecast

A pandas notebook in Fastero's editor. Invented sample data, defined in the cell.

FAQ

Why does pandas use so much memory?

pandas keeps the whole DataFrame in RAM, uses 8 bytes for every number by default, and stores text with per-value overhead. Many operations also build a full new DataFrame before the old one is freed, so the peak can be several times the DataFrame's size.

How do I check how much memory a DataFrame uses?

Run df.info(memory_usage="deep") for the total, or df.memory_usage(deep=True) for bytes per column. Without deep, text stored as object is counted as pointers only. For object text with many repeated values, deep=True can overcount, because it sizes a shared string once per row.

Does converting to category save memory?

Yes, when values repeat: five text columns with 3 to 60 distinct values went from 388 MB to 24 MB on 5 million rows. On a column of unique values it makes things worse; a unique ID grew from 105 MB to 125 MB.

How do I fix MemoryError: Unable to allocate in pandas?

Find what asked for the memory: the message gives the array's size and shape. If it's a pivot or merge, check the row or cell count first; if it's loading, read fewer columns with smaller types. If the data still doesn't fit, use DuckDB or Polars, process the file in chunks, or use a machine with more RAM.

Why does my pandas merge run out of memory?

The key repeats on both sides, so pandas returns every matching pair: a key repeated 3 times on each side gives 9 rows. Pass validate="many_to_one" to get an error instead, and deduplicate or aggregate the lookup table before merging.

Is pandas 3 more memory efficient than pandas 2?

For text, usually, if pyarrow is installed: a pyarrow string costs about 8 bytes plus its characters, with no Python object per value, and copy-on-write avoids many copies. Without pyarrow, pandas 3's str falls back to Python objects and measured the same as pandas 2's object.

Sources

Read on 2 December 2026.


Try Fastero free: pandas notebooks next to your team's data, and on Pro a 16 GB machine for $0.40 an hour when a load really needs it. No credit card required.

Ready to try it yourself?

Connect your database, ask questions in plain English, and get live dashboards — in under 2 minutes. No credit card required.

Follow Fastero on LinkedIn for new articles and examples.