Sub topic 1
Measuring memory: memory_usage(deep=True) and info()
You can't shrink a DataFrame until you know where its memory goes. This chapter shows how to measure memory per column, why the default measurement can be badly wrong for string columns, and how to read the summary that info() prints.
Prerequisites
This chapter assumes you can:
- Write basic Python and work with NumPy arrays.
- Create and index pandas DataFrames.
- Recognize pandas dtypes such as
int64,float64andobject.
Building a sample DataFrame
The examples in this tutorial use one DataFrame with 100,000 rows. It has three numeric columns and one string column with only five distinct values.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 100_000
df = pd.DataFrame({
"user_id": rng.integers(0, 50_000, n),
"age": rng.integers(18, 90, n),
"score": rng.random(n),
"country": rng.choice(["US", "DE", "FR", "JP", "BR"], n),
})
print(df.dtypes)NumPy creates integers as int64 and floats as float64 by default, and pandas keeps those dtypes. Each value in those columns takes 8 bytes.
Measuring with memory_usage
DataFrame.memory_usage() returns a Series with the bytes used by the index and by each column. By default it counts only the array that holds the column. For an object column, that array holds 8-byte pointers to Python objects. The default does not count the objects themselves.
deep=True follows each pointer and adds the size of the object it points to.
print(df.memory_usage()) # shallow
print(df.memory_usage(deep=True)) # deep
print(df.memory_usage(deep=True).sum())On pandas 2.x, the numeric columns report 800,000 bytes each (100,000 values at 8 bytes) in both calls. The country column is the difference. The shallow count shows 800,000 bytes. The deep count is several times larger, about 5.9 MB, because each two-character Python string takes roughly 51 bytes and deep counting adds that cost once per row, even when many rows hold the same text. Exact figures vary by Python and pandas version.
If you use pandas 3 or later, string columns default to a dedicated string dtype, and the dtypes output shows str instead of object. The measurement approach is the same. The numbers for the string column will differ from the ones above.
Reading info()
df.info() prints a compact summary: the index type, the column names, non-null counts, dtypes, and a total memory figure.
df.info()
df.info(memory_usage="deep")The memory line in the first call ends with a plus sign, such as 5.1+ MB. The plus sign means the figure is a lower bound, because it was computed without inspecting the objects in object columns. The second call passes memory_usage="deep", drops the plus sign, and reports the true total.
For large frames, deep inspection of object columns can be slow. That is the trade-off for an accurate number.
What to look at in the output
The two tools answer different questions:
| Tool | Per-column bytes | Deep option | Best for |
|---|---|---|---|
| `memory_usage(deep=True)` | Yes, as a Series | `deep=True` | Ranking columns and computing totals in code |
| `info(memory_usage="deep")` | No, total only | `memory_usage="deep"` | A quick look at dtypes, nulls and the total |
Use memory_usage(deep=True) when you need numbers you can sort, compare or plot. Use info() when you want to see dtypes and null counts next to the total.
A baseline to compare against
Later chapters shrink each column and compare the result with a starting figure. Save that figure now, together with the per-column breakdown, so you can see which changes paid off.
baseline = df.memory_usage(deep=True)
print(baseline.sort_values(ascending=False))
print(f"Total: {baseline.sum():,} bytes")On the sample data, country should rank first by a wide margin. It has only five distinct values, which makes it a good candidate for the category dtype covered later in this tutorial. The three numeric columns are fixed at 8 bytes per value until you choose smaller dtypes.
Exercise
You call df.memoryusage() and df.memoryusage(deep=True) on a DataFrame with one object column of short strings. The numeric columns report the same size in both calls, but the object column is much larger with deep=True. Why does the deep figure differ, and which one should you trust when planning savings?
Show answer
The default count measures only the column's array, which holds 8-byte pointers for an object column. deep=True also adds the size of each Python string the pointers refer to, once per row. Trust the deep figure, because it reflects the memory the strings actually occupy.
Exercise
df.info() ends with "memory usage: 5.1+ MB". What does the plus sign mean, and how do you get an exact figure?
Show answer
The plus sign means the number is a lower bound, because object columns were not inspected deeply. Call df.info(memory_usage="deep") to get the exact total.