Sub topic 1
Why Large Files Do Not Fit in Memory
Prerequisites
This chapter assumes basic Python loops and context managers, familiarity with pandas DataFrame objects and read_csv, and basic groupby operations.
Why Large Files Do Not Fit in Memory
A pandas DataFrame is held in the computer's RAM. Reading a large CSV creates columns, indexes, and temporary objects in memory. The CSV file's size on disk is therefore not a reliable memory estimate. Text columns, for example, can use much more memory after pandas converts them into Python strings.
If the file and temporary objects need more RAM than the system can provide, the process may become very slow or raise a MemoryError. Chunking avoids this by loading only part of the file at a time.
Measuring How Much Memory a DataFrame Uses
Use memory_usage(deep=True) to measure the memory used by columns, including the contents of object or string columns. A sample helps estimate a suitable chunk size before processing the entire file.
import pandas as pd
sample = pd.read_csv("big.csv", nrows=100_000)
memory_mib = sample.memory_usage(deep=True).sum() / 1024**2
print(f"{memory_mib:.1f} MiB")
print(sample.dtypes)The estimate must include working memory used by filtering, sorting, or grouping. Leave room for the operating system and other applications.
> callout note > Measure a representative sample. A small sample with unusually short strings can underestimate the real memory requirement.
Reading a CSV in Chunks with `chunksize`
Pass chunksize to read_csv. Pandas returns a reader that produces DataFrames with at most that many rows.
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)Working with the Chunk Reader
A reader can be used in a with statement, which closes it when processing finishes:
import pandas as pd
with pd.read_csv("big.csv", chunksize=50_000) as reader:
for chunk in reader:
print(len(chunk))You can also advance it manually. get_chunk() reads the next default-sized chunk, while get_chunk(n) requests a specific number of rows.
import pandas as pd
reader = pd.read_csv("big.csv", chunksize=50_000)
first = reader.get_chunk()
next_part = reader.get_chunk(1_000)
reader.close()Exercise
Why can chunksize=100_000 prevent a large CSV from exhausting memory?
Show answer
It keeps only one group of up to 100,000 rows in the DataFrame at a time, allowing each group to be processed and released before the next one is read.