Sub topic 1
Why Large Files Do Not Fit in Memory
Prerequisites
This chapter assumes you know basic Python, including loops and context managers. It also assumes you have used pandas DataFrames and read_csv, and that you can write a simple groupby aggregation. The rest of the tutorial builds on this chapter's working model of memory.
The problem
A call like pd.read_csv("big.csv") loads the whole file into one DataFrame. A DataFrame lives in RAM (random access memory), the fast working memory of your computer. If the DataFrame needs more RAM than is free, the operating system starts swapping data to disk, which is very slow, or the Python process is killed. You may see a MemoryError or the process may simply disappear.
The key point is that a CSV file on disk and a DataFrame in memory are different representations of the same data. The DataFrame is usually larger than the file.
Why memory use exceeds file size
Three things make a DataFrame bigger than its CSV:
- Text becomes Python objects. Columns of strings use the
objectdtype. Each value is a separate Python string object with its own overhead, often 50 bytes or more even for short text. In a CSV, a three-letter code takes about three bytes. - Numbers use fixed widths. By default pandas stores integers as
int64and decimals asfloat64, 8 bytes each. The value7takes one byte in a CSV but eight in memory. - Operations make copies. Filtering, sorting, merging, and adding columns often create temporary copies. A 4 GiB DataFrame can need 8 GiB or more to work on.
As a rough rule, expect a DataFrame to need two to ten times the size of its CSV file, depending on how much of the data is text.
A quick estimate
You can see the effect by reading a small sample and checking its memory use. This is a preview of a technique covered in the next chapter.
import os
import pandas as pd
sample = pd.read_csv("big.csv", nrows=100_000)
sample_mib = sample.memory_usage(deep=True).sum() / 1024**2
print(f"Sample in memory: {sample_mib:.1f} MiB")
print(sample.dtypes)
file_mib = os.path.getsize("big.csv") / 1024**2
print(f"File on disk: {file_mib:.1f} MiB")The nrows argument reads only the first 100,000 rows. The deep=True option counts the real size of string objects, not just their pointers. Divide the sample's memory by its row count, then multiply by the total row count to estimate the full load.
The idea behind chunking
Most tasks do not need every row at the same time. Counting rows, summing a column, or keeping only the rows that match a condition can all be done on a piece of the file, with the pieces' results combined afterward.
Chunking means reading the file in pieces of a fixed number of rows. You process one piece, keep only a small result, and discard the piece before reading the next one. Peak memory depends on the chunk size, not on the file size.
The tutorial's later chapters show how to do this with the chunksize argument of read_csv. The basic shape looks like this:
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)Here read_csv returns an iterator of DataFrames. Each chunk holds up to 100,000 rows, and only one chunk is in memory at a time.
What chunking costs
Chunked code is longer than a one-line read_csv. You must decide what to keep from each chunk and how to combine the results. The file is also parsed once per pass, so a task that needs several passes takes longer. In exchange, a file of any size can be processed with a fixed memory budget.
Exercise
A 3 GiB CSV file has many text columns. You try pd.read_csv on a machine with 4 GiB of free RAM. Why might it fail even though the file is smaller than the RAM, and what does chunking change?
Show answer
The DataFrame is usually larger than the file. Text columns become separate Python objects with overhead, numeric columns use 8 bytes per value by default, and operations create temporary copies, so the data can need well over 4 GiB. Chunking reads a fixed number of rows at a time, so peak memory depends on the chunk size instead of the file size.