Sub topic 1
Why large files do not fit in memory
A CSV file that is a few gigabytes on disk can fail to load with pd.read_csv. The machine may have more free RAM than the file's size and still run out. This chapter explains why. It also gives you a way to judge, before you load anything, whether a file is likely to fit. The rest of the tutorial then shows how reading in chunks avoids the problem.
Prerequisites
This chapter assumes you already have:
- Basic Python, including loops and context managers.
- Familiarity with pandas DataFrames and
read_csv. - Basic
groupbyand aggregation in pandas.
You do not need any knowledge of how Python or pandas manage memory internally.
The failure you are trying to avoid
The default call is the simplest way to read a CSV:
import pandas as pd
df = pd.read_csv("big.csv")This call reads the whole file, converts every value to a Python or NumPy type, and keeps all of it in RAM at once. If the result does not fit, one of three things happens:
- Python raises
MemoryError, or NumPy raises an "Unable to allocate" error for a single large array. - The operating system starts using swap (disk used as slow overflow memory). The program gets very slow but may finish.
- The operating system's out-of-memory killer ends the process. You see a message such as
Killed, with no Python traceback.
The third case is the most confusing. Nothing in your code is wrong, and no exception appears.
Disk size is not memory size
A file on disk is text. A DataFrame holds typed values in memory, and the two representations differ in size. The difference is usually in the wrong direction: the DataFrame is often larger than the file.
The next script builds a one-million-row CSV and compares its size on disk with the size of the loaded DataFrame.
import os
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 1_000_000
df = pd.DataFrame(
{
"id": np.arange(n),
"region": rng.choice(["north", "south", "east", "west"], size=n),
"amount": rng.random(n) * 100,
"note": rng.choice(["ok", "late", "refund", "gift card"], size=n),
}
)
df.to_csv("demo.csv", index=False)
file_mib = os.path.getsize("demo.csv") / 1024**2
loaded = pd.read_csv("demo.csv")
frame_mib = loaded.memory_usage(deep=True).sum() / 1024**2
print(f"file on disk: {file_mib:7.1f} MiB")
print(f"DataFrame in RAM: {frame_mib:7.1f} MiB")
print(f"ratio: {frame_mib / file_mib:7.2f}")The exact numbers depend on your pandas version and on the data. With pandas 2.x and text columns like these, the DataFrame is typically larger than the file. Run it and look at the ratio on your own machine.
Several effects cause this gap.
Text columns carry per-value overhead
Before pandas 3, the default dtype for strings is object. An object column stores one pointer (8 bytes on a 64-bit build) per row, and each pointer refers to a separate Python string object. A Python string object has a header of roughly 49 bytes plus its characters. The text ok takes 2 bytes in the file, but a Python string holding it is far larger. Newer pandas versions can store strings more compactly, but you should still measure instead of assuming.
Numbers are stored at a fixed width
On disk, the value 7 takes 1 character. In an int64 column it takes 8 bytes, whatever its size. A float such as 12.5 takes 4 characters in the file and 8 bytes as float64. For short numbers, memory is larger than the file. For long floats written with 17 digits, memory is smaller. A file full of short integers expands the most.
Missing values can change the dtype
An integer column that contains missing values is read as float64 by default, because NumPy integers cannot hold NaN. The column stays at 8 bytes per value, but the dtype is no longer what you expected. Later chapters return to this.
The index adds a column
Every DataFrame has an index. The default RangeIndex is cheap because it stores only start, stop and step. After operations such as filtering or concatenating, the index may become a materialized integer array with 8 more bytes per row.
Fixed-width arithmetic
For numeric columns you can calculate the memory use directly. The cost is rows × bytes per value, per column.
| dtype | Bytes per value | 100 million rows, one column |
|---|---|---|
| `int8` | 1 | about 0.09 GiB |
| `int32` | 4 | about 0.37 GiB |
| `int64` | 8 | about 0.75 GiB |
| `float64` | 8 | about 0.75 GiB |
| `object` (strings) | 8 for the pointer, plus the string objects | often several GiB |
The following function turns that arithmetic into a quick estimate:
import numpy as np
def fixed_width_gib(rows, dtypes):
"""Memory in GiB for numeric columns of the given dtypes."""
per_row = sum(np.dtype(d).itemsize for d in dtypes)
return rows * per_row / 1024**3
print(round(fixed_width_gib(200_000_000, ["int64", "float64", "float64"]), 2))This prints 4.47. Two hundred million rows of just three numeric columns already need about 4.5 GiB, before any string column and before any working copies.
This function cannot estimate string columns, because their cost depends on the length and repetition of the values. The next chapter shows how to measure them from a sample.
Peak memory is higher than final memory
The size of the finished DataFrame is a lower bound. You also need room for what happens around it.
flowchart LRThe diagram block must follow the required format, so here is the real one:
Several common operations create copies:
- Parsing. The parser reads the file in internal blocks and then assembles columns. During assembly, some data exists in more than one form.
- Filtering.
df[df["status"] == "error"]builds a boolean mask the length of the frame, then a new DataFrame with the matching rows. The original is still alive while you hold a reference to it. - Sorting, merging and
concat. These usually produce new frames. A merge can need several times the size of its inputs. groupbyandapply. These create intermediate arrays and per-group objects.- Assigning back.
df = df.sort_values("id")keeps the old frame alive until the assignment finishes.
A common guideline is that a full-load workflow needs between two and five times the in-memory size of the data, depending on what you do with it. Treat this as a rule of thumb and not a measured law. A pipeline that only reads and sums may stay close to 1x. A pipeline that merges and sorts may exceed 5x.
What "fits" really means
The memory available to your process is less than the machine's installed RAM. Subtract:
- The operating system and other running programs.
- The Python interpreter, pandas and NumPy themselves, which take a few hundred MiB.
- Any limit imposed by a container, a notebook service or a job scheduler. A container limited to 4 GiB of memory is killed at 4 GiB, even on a host with 64 GiB.
- Other objects already in your session. Notebooks often hold several old DataFrames that are no longer needed but are still referenced.
A 32-bit Python build is limited to a few GiB of address space regardless of installed RAM. Almost all current installs are 64-bit, but it is worth checking in unusual environments.
The idea behind chunking
The failure comes from a single decision: loading all rows at once. Many tasks do not need all rows at once. Counting rows, summing a column, filtering for errors and computing a mean per region each need only a running result and the current batch of rows.
Chunked processing relies on that fact. You read a bounded number of rows, process them, keep only a small result, and then discard the rows and read the next batch. Memory use depends on the chunk size and the size of the results. It does not depend on the file size.
The core API is one argument to read_csv:
import pandas as pd
total_rows = 0
for chunk in pd.read_csv("big.csv", chunksize=100_000):
total_rows += len(chunk)
print(total_rows)With chunksize, read_csv returns an iterator instead of a DataFrame. Each loop step yields a DataFrame of up to 100,000 rows. Only one chunk is held at a time, so the program can process a file much larger than RAM. The next chapters cover how to measure, size, filter and aggregate with this pattern.
A checklist before you load a large file
Run through these questions before calling read_csv on a file you have not seen before:
- How large is the file on disk, and how many rows does it have?
- Which dtypes will the columns get? Any string columns?
- How much memory does your process actually have, after limits and other usage?
- Which operations come after loading, and which of them create copies?
- Does the task need all rows together, or can it work from running results?
If the estimated peak is close to your available memory, chunk the read instead of hoping it fits.
Exercise
A CSV has 50 million rows and four numeric columns, which pandas reads as int64, int64, float64 and float64. (a) How many GiB do these columns need in memory, to two decimal places? (b) The process has 4 GiB available, and your script filters the frame and sorts the result. Is a full load safe, and why?
Show answer
(a) Each column uses 8 bytes per value, so 4 columns use 32 bytes per row. 50,000,000 × 32 = 1.6 billion bytes, which is 1.6e9 / 1024**3 ≈ 1.49 GiB. (b) It is not safe. The loaded frame alone takes about 1.49 GiB, and filtering creates a mask and a second frame, while sorting creates another copy. With the rule of thumb of two to five times the data size, the peak could be roughly 3 to 7 GiB, which can exceed the 4 GiB limit. Reading in chunks, and sorting only the reduced result, avoids the risk.