Sub topic 2
Measuring how much memory a DataFrame uses
This chapter assumes you know basic pandas, including read_csv, and you can read a short Python loop. Before you pick a chunk size, you need to know how much memory your rows take. Here you will measure it and use a small sample to estimate the cost of the whole file.
Why the file size misleads you
A 2 GB CSV does not become a 2 GB DataFrame. Text numbers become fixed-width integers or floats. Repeated strings become separate Python objects. A DataFrame is often larger than its file, sometimes several times larger. You need to measure it.
Using memory_usage
DataFrame.memory_usage() returns the bytes used by each column and by the index.
import pandas as pd
df = pd.DataFrame({
"id": range(1000),
"region": ["north", "south", "east", "west"] * 250,
"amount": [19.99] * 1000,
})
print(df.memory_usage())
print(df.memory_usage(deep=True))
print(df.memory_usage(deep=True).sum() / 1024**2, "MiB")The two calls give different numbers for the region column. A string column has dtype object. It stores one 8-byte pointer per row, and the strings live elsewhere in memory. The default call counts only the pointers. deep=True follows the pointers and adds the size of the strings. Use deep=True whenever a column holds text.
The result is a Series with one entry per column, plus an Index entry. Call .sum() for the total.
You can get a similar report with df.info(memory_usage="deep"). It also lists dtypes and non-null counts.
Estimating from a sample
You cannot call memory_usage on a DataFrame you cannot load. Read a sample instead, then scale up.
import pandas as pd
sample = pd.read_csv("big.csv", nrows=100_000)
sample_bytes = sample.memory_usage(deep=True).sum()
print(sample_bytes / 1024**2, "MiB")
print(sample.dtypes)
bytes_per_row = sample_bytes / len(sample)
with open("big.csv", "rb") as f:
total_rows = sum(1 for _ in f) - 1 # minus the header line
print(f"Estimated full size: {bytes_per_row * total_rows / 1024**3:.1f} GiB")Reading dtypes shows which columns are object. Those are the first candidates for savings, which a later chapter covers.
Limits of the estimate
- The sample may not represent the file. The first rows can have short strings or no missing values. If later rows differ, the real cost is higher. Treat the estimate as a lower bound.
- Counting lines can be wrong. A quoted field that contains a newline spans two lines. For an exact count, add up
len(chunk)over a chunked read. - Peak memory is higher than the final DataFrame. Parsing and copying temporarily need extra space. Leave generous headroom, often two to three times the estimated size.
What to do with the number
Compare the estimate with the memory you can spare. If it fits with headroom, a single read_csv call is fine. If it does not, chunking is the next step. The chunk size is then roughly your memory budget divided by bytes_per_row. The next chapters build on this.
Exercise
A sample of 50,000 rows uses 40 MiB when measured with memory_usage(deep=True). The file has 5,000,000 rows. About how much memory does the full DataFrame need, and why might the real figure be higher?
Show answer
5,000,000 / 50,000 is 100, so the estimate is about 4,000 MiB (roughly 3.9 GiB). The real figure may be higher because the sample might not represent later rows, for example if they have longer strings, and because parsing needs extra temporary memory beyond the final DataFrame.