Sub topic 2
Measuring how much memory a DataFrame uses
This chapter assumes you can read a CSV with pd.read_csv, you know what a DataFrame and a dtype are, and you are comfortable with basic Python loops. You will learn how to measure what a DataFrame costs in memory, why the number pandas gives you can be wrong, and how to use a small sample to plan a chunked read.
Why measure before you chunk
The previous chapter explained that a file too large for RAM cannot be loaded into one DataFrame. The size of the file on disk is only a rough guide to how much memory it will need. A 2 GB CSV can need 1 GB or 10 GB once loaded, depending on the columns and their dtypes.
Measuring gives you three things:
- An estimate of how many rows fit in the memory you can spare.
- A way to see which columns cost the most, so you can shrink them.
- A basis for choosing a chunk size instead of guessing.
The cheapest way to measure is to read a small piece of the file, measure that, and scale up.
Where DataFrame memory goes
Each column of a DataFrame has a dtype, and the dtype determines how the values are stored.
- Numeric dtypes such as
int64andfloat64use a fixed number of bytes per value. Anint64column with 1,000,000 rows uses 8,000,000 bytes. booluses 1 byte per value.- Datetime columns (
datetime64[ns]) use 8 bytes per value. objectcolumns, which is what pandas uses for strings by default in many versions, store a pointer to a separate Python string for each value. The pointer costs 8 bytes, and each string object costs its own memory on top of that, often 50 bytes or more for short text.categorycolumns store small integer codes plus one copy of each distinct value.
This is why text-heavy files are the expensive ones. A column of 1,000,000 short strings can take several times the memory of a column of 1,000,000 integers.
Using memory_usage
DataFrame.memory_usage() returns a Series with one entry per column (and one for the index), measured in bytes.
import pandas as pd
df = pd.DataFrame(
{
"id": range(5),
"city": ["Paris", "Berlin", "Madrid", "Rome", "Vienna"],
"price": [1.5, 2.5, 3.5, 4.5, 5.5],
}
)
print(df.memory_usage())The output lists Index, id, city and price. For id and price the figure is exact: 5 rows times 8 bytes is 40 bytes. For city, the default figure is only 40 bytes as well. That is the cost of five pointers, not of the strings themselves.
The deep=True argument
By default, memory_usage counts only the array that holds the values. For object columns, that array holds pointers. To include the size of the Python objects they point to, pass deep=True.
import pandas as pd
df = pd.DataFrame(
{
"id": range(5),
"city": ["Paris", "Berlin", "Madrid", "Rome", "Vienna"],
"price": [1.5, 2.5, 3.5, 4.5, 5.5],
}
)
print(df.memory_usage())
print(df.memory_usage(deep=True))Compare the two outputs. The city entry is much larger with deep=True, because it now includes each string object. Numeric columns do not change.
Total size and the index
The result of memory_usage is a Series, so .sum() gives the total in bytes. Divide by 1024**2 for MiB.
total_bytes = df.memory_usage(deep=True).sum()
print(total_bytes / 1024**2, "MiB")The index is included by default. Pass index=False to leave it out. A default RangeIndex costs almost nothing, so this rarely matters, but a large index of strings can.
df.info as a quick check
df.info(memory_usage="deep") prints the dtypes, non-null counts and a total in one view.
df.info(memory_usage="deep")Plain df.info() shows a total with a trailing + when it did not inspect object columns deeply. That plus sign is a reminder that the figure is a lower bound.
Estimating from a sample
You cannot call memory_usage on a DataFrame you cannot load. Instead, read the first rows with nrows and measure those.
import pandas as pd
chunk = pd.read_csv("big.csv", nrows=100_000)
print(chunk.memory_usage(deep=True).sum() / 1024**2, "MiB")
print(chunk.dtypes)This reads 100,000 rows, reports their size in MiB, and shows which dtype pandas chose for each column. The dtype listing is as useful as the number. A column you expect to be numeric that shows up as object is a sign of messy values, and an int64 column that only holds small values is a candidate for a smaller dtype.
Scaling up to the whole file
If the sample holds n rows and uses m MiB, the memory per row is m / n. Multiply by the total row count for a rough full-file estimate. You can count rows without loading the data by iterating in chunks, as shown earlier in this tutorial.
import pandas as pd
sample_rows = 100_000
sample = pd.read_csv("big.csv", nrows=sample_rows)
bytes_per_row = sample.memory_usage(deep=True).sum() / sample_rows
total_rows = 0
for chunk in pd.read_csv("big.csv", usecols=[0], chunksize=500_000):
total_rows += len(chunk)
estimate_gib = bytes_per_row * total_rows / 1024**3
print(f"about {estimate_gib:.1f} GiB if loaded at once")The usecols=[0] argument makes the counting pass cheaper, because only one column is parsed.
How a sample can mislead you
The first rows of a file are not always typical. Be aware of these cases:
- Sorted files. If the file is sorted by a column, the first rows may have short strings or missing values that do not represent the rest.
- Growing text. Free-text fields such as comments can be longer in later rows.
- Late type changes. A column that looks like
int64in the sample may contain a text value 5 million rows later. That makes pandas pickobjectfor that column in a full read. - Memory beyond the DataFrame. While parsing, pandas and Python need extra working memory. Peak usage during
read_csvcan be higher than the final DataFrame size.
Treat the estimate as an approximate figure, and leave a safety margin. A common rule of thumb is to plan for the DataFrame to use no more than a third to a half of the memory available, because operations such as groupby, merge and sort_values often create copies.
Seeing which columns cost the most
memory_usage(deep=True) is also a diagnostic. Sort it to find the expensive columns.
import pandas as pd
sample = pd.read_csv("big.csv", nrows=100_000)
usage = sample.memory_usage(deep=True).sort_values(ascending=False)
print((usage / 1024**2).round(2))Typically one or two object columns dominate. Those are the first targets for the techniques in the "Reading less" chapter: dropping columns you do not need with usecols, and choosing smaller dtypes.
Testing a dtype change
You can check the effect of a change on the sample before you apply it to the whole file.
import pandas as pd
sample = pd.read_csv("big.csv", nrows=100_000)
before = sample.memory_usage(deep=True).sum()
smaller = sample.copy()
for col in smaller.select_dtypes(include="object").columns:
if smaller[col].nunique() < 0.5 * len(smaller):
smaller[col] = smaller[col].astype("category")
after = smaller.memory_usage(deep=True).sum()
print(f"{before / 1024**2:.1f} MiB -> {after / 1024**2:.1f} MiB")Converting a string column with many repeated values to category often cuts its memory by an order of magnitude. A column where almost every value is unique gains nothing, which is why the code checks nunique first.
Turning the measurement into a plan
The diagram shows how the pieces fit together.
A simple calculation turns the measurement into a chunk size:
import pandas as pd
sample_rows = 100_000
sample = pd.read_csv("big.csv", nrows=sample_rows)
bytes_per_row = sample.memory_usage(deep=True).sum() / sample_rows
budget_bytes = 500 * 1024**2 # allow about 500 MiB for one chunk
chunk_rows = int(budget_bytes / bytes_per_row)
print(chunk_rows)Here the budget is for a single chunk, not the whole job. Pick a number well below your free memory, since your processing code needs room to create temporary results. The next chapters use this idea when they read the file in chunks.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Calling `memory_usage()` without `deep=True` | Understates string columns badly | Use `deep=True` |
| Using file size on disk as the memory estimate | Off by a large factor in either direction | Measure a sample |
| Measuring only the first rows of a sorted file | Sample is not representative | Also sample from later in the file, for example with `skiprows` |
| Ignoring working memory | Out-of-memory errors during parsing or `groupby` | Keep chunk size well under the free memory |
| Trusting dtypes inferred from a sample | Later rows break the assumption | Declare dtypes explicitly when reading |
To sample from the middle of a file, skip a block of data rows while keeping the header:
import pandas as pd
middle = pd.read_csv(
"big.csv",
skiprows=range(1, 5_000_001), # skip data rows 1 to 5,000,000, keep the header
nrows=100_000,
)
print(middle.memory_usage(deep=True).sum() / 1024**2, "MiB")Comparing this figure with the one from the start of the file shows how much the row size varies.
Exercises
Exercise
A DataFrame has one object column of short strings and 2,000,000 rows. df.memory_usage().sum() reports about 16 MB, but the process uses much more memory than that. Which call gives a better estimate, and why does the first one report too little?
Show answer
Use df.memory_usage(deep=True).sum(). Without deep=True, pandas counts only the array of 8-byte pointers for the object column (2,000,000 times 8 bytes, which is 16 MB). It does not count the Python string objects the pointers refer to. With deep=True, those objects are included.
Exercise
You read 50,000 rows of a CSV with nrows=50_000. memory_usage(deep=True).sum() gives 40 MiB. The file has 10,000,000 rows. Roughly how much memory would a full load need, and what chunk size in rows would keep one chunk near 200 MiB?
Show answer
Memory per row is 40 MiB / 50,000 = 0.0008 MiB. The full load needs about 0.0008 x 10,000,000 = 8,000 MiB, close to 7.8 GiB. For a 200 MiB chunk, divide 200 by 0.0008 to get 250,000 rows. The real peak will be higher because of parsing overhead, so a smaller chunk such as 100,000 to 200,000 rows is a safer choice.