Sub topic 7
Measuring memory: shallow versus deep
This chapter assumes you know how a DataFrame is organized as typed columns, what the object dtype is (an array of pointers to Python objects), and the difference between NumPy dtypes and extension dtypes. You should be comfortable reading df.dtypes. Here you learn what pandas reports when you ask how much memory a DataFrame uses, why two answers can differ by a factor of seven, and which numbers to trust.
Why there are two answers
Every pandas memory figure comes from one question: which bytes do you count?
- Shallow counts only the memory owned by the column's array. For a NumPy dtype like
int64, that is everything. For anobjectcolumn, it is the array of 8-byte pointers and nothing they point to. - Deep also follows each pointer and adds the size of the Python object it refers to. For a string column, that means adding the size of every string object.
Fixed-width columns give the same answer either way. Object columns do not. A shallow figure for an object column is a lower bound that can be far below the real cost.
The tools
pandas gives you three entry points.
| Tool | What it returns | Deep option |
|---|---|---|
| `Series.memory_usage(index=True, deep=False)` | Bytes for one column, plus the index by default | `deep=True` |
| `DataFrame.memory_usage(index=True, deep=False)` | A Series of bytes per column, with an `Index` row first | `deep=True` |
| `DataFrame.info(memory_usage=None)` | A printed summary with a total | `memory_usage="deep"` |
All sizes are in bytes. The index argument controls whether the row index is counted. Pass index=False when you want to compare columns without the index's contribution. The index is small for a default RangeIndex (it stores only start, stop, and step, roughly 130 bytes), but a string or datetime index can be large.
Worked example: object versus numeric columns
Start with a frame that has one column of each common kind.
import pandas as pd
n = 300_000
df = pd.DataFrame({
"id": range(n),
"score": [0.5] * n,
"active": [True] * n,
"city": ["Oslo", "Lima", "Pune"] * (n // 3),
})
print(df.dtypes)
print(df.memory_usage(index=False))
print(df.memory_usage(index=False, deep=True))The shallow result is exactly what the dtype arithmetic predicts:
idisint64: 300,000 × 8 = 2,400,000 bytes.scoreisfloat64: 2,400,000 bytes.activeisbool: 300,000 × 1 = 300,000 bytes.cityisobject: 300,000 × 8 = 2,400,000 bytes, which is only the pointers.
The deep result is identical for the first three columns. For city it is much larger, about 18 million bytes on a typical 64-bit CPython. The extra roughly 15.9 million bytes is 300,000 string objects at about 53 bytes each (a 4-character ASCII string has about 49 bytes of overhead plus its characters). You can check one string yourself:
import sys
print(sys.getsizeof("Oslo"))On CPython 3.x for 64-bit platforms this prints 53. The exact number varies with the Python version, and non-ASCII text takes more per character.
What `info()` prints
DataFrame.info() ends with a memory line. By default it does not follow pointers, so when the frame has object columns the figure carries a plus sign.
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima", "Pune"] * 100_000})
df.info()
df.info(memory_usage="deep")The first call prints a line like memory usage: 2.3+ MB. The + means "at least this much, and probably more, because object columns were counted shallowly". The second call prints a figure around 17 MB with no plus sign, because every string was measured.
info() also has a cost: deep mode walks every Python object. On a frame with tens of millions of string cells, it can take noticeable time. For a first estimate on a very large frame, measure a sample and scale up:
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima", "Pune"] * 1_000_000})
sample = df.sample(100_000, random_state=0)
per_row = sample.memory_usage(index=False, deep=True).sum() / len(sample)
print(round(per_row * len(df) / 1e6), "MB estimated")Sampling works well when string lengths are fairly uniform. It underestimates if a few rows hold very long strings that the sample misses.
How deep counting works, and where it misleads
Deep counting for an object column calls sys.getsizeof on each element and adds the results. Three consequences follow.
Shared objects are counted once per reference. In the examples above, the list ["Oslo", "Lima", "Pune"] * n repeats three string objects, so the process really holds only three strings. Deep mode still reports 300,000 of them. You can see the gap:
import sys
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima", "Pune"] * 100_000})
unique = {id(x): x for x in df["city"]}
real = sum(sys.getsizeof(x) for x in unique.values())
print(len(unique), "distinct objects,", real, "bytes")
print(df["city"].memory_usage(index=False, deep=True), "bytes by deep count")Here the true string payload is a few hundred bytes. Whether strings are shared depends on how the data was created. Strings parsed from a CSV are usually separate objects, one per cell, so the deep figure is accurate for data loaded from files. Strings built from a short repeated list, as in tutorials, can be heavily shared. Deep mode cannot tell the difference.
Only sys.getsizeof is counted. Deep mode measures each object's own size. If a cell is a list or a dict, it counts the container but not the items inside it. A column of lists of strings is therefore still underestimated.
Allocator overhead is invisible. The figure is the sum of object sizes. The operating system sees more, because Python rounds allocations and fragments memory. A process-level tool will report a higher number than memory_usage(deep=True).
Extension dtypes and measurement
Extension dtypes report their own storage, so their shallow and deep figures often agree more closely than for object. A masked nullable integer such as Int64 stores an int64 data array plus a boolean mask, so it costs 9 bytes per value instead of 8.
import pandas as pd
n = 1_000_000
plain = pd.Series(range(n))
nullable = pd.Series(range(n), dtype="Int64")
print(plain.memory_usage(index=False))
print(nullable.memory_usage(index=False))The first line prints 8,000,000 and the second prints 9,000,000. This is the price of keeping integers when values can be missing. Compare it with the default alternative, float64 with NaN, which costs 8 bytes per value but changes the values to floats.
A categorical column reports the codes array plus the categories. Because the categories are a small set of strings, the deep figure is a good estimate of true cost. The next chapter uses this to show large savings on repeated values.
Measuring one column versus a whole frame
When you need to find which column to fix, work column by column and sort:
import pandas as pd
df = pd.DataFrame({
"id": range(200_000),
"score": [0.5] * 200_000,
"city": ["Oslo", "Lima", "Pune", "Rome"] * 50_000,
"note": ["ok"] * 200_000,
})
usage = df.memory_usage(index=False, deep=True).sort_values(ascending=False)
print(usage)
print((usage / usage.sum()).round(3))
print("total MB:", round(usage.sum() / 1e6, 1))The share column shows where the memory goes. In frames with text, one or two object columns usually hold most of the total, so those are the columns worth converting first.
Checking the arithmetic with `nbytes`
For NumPy-backed columns you can confirm the figure from the underlying array. nbytes is the number of elements times the item size.
import pandas as pd
s = pd.Series(range(1_000_000))
arr = s.to_numpy()
print(arr.dtype, arr.itemsize, arr.nbytes)
print(s.memory_usage(index=False))Both lines report 8,000,000 bytes. If memory_usage(index=False) and nbytes disagree for a numeric column, something is wrong with your assumption about the dtype. For an object array, nbytes is again only the pointer array, which is the shallow figure.
Views, copies, and double counting
Memory figures are per object. If two DataFrames share the same underlying arrays, each reports its full size, and adding them double counts. This happens with views and with Copy-on-Write, where a "copy" shares memory until one side is modified. Summing memory_usage across many related frames can therefore overstate real use. When in doubt, check the process: compare resident memory before and after creating the frame, using a tool such as psutil or your operating system's monitor.
Common errors
- Trusting the default. Calling
df.memory_usage()withoutdeep=Trueand concluding that a text-heavy frame is small. The result looks plausible because it is a clean multiple of 8. - Forgetting the index. Comparing a column's
memory_usage()(index included by default) with a figure computed fromnbytes(index not included). Useindex=Falseto compare like with like. - Reading the
+as noise. The plus sign ininfo()marks a lower bound. - Assuming deep is exact. It is an estimate that counts shared objects repeatedly and misses nested container contents.
- Measuring after the fact only. Peak memory during loading and transformation is often larger than the final frame. Measure the steps that matter.
Summary
Shallow memory counts the column's own array. Deep memory also counts the Python objects an object column points to. They match for NumPy numeric, boolean, and datetime columns and differ greatly for strings. Use memory_usage(deep=True) or info(memory_usage="deep") before deciding that a frame is small, find the heaviest columns by sorting the per-column result, and remember that peak memory during operations is a separate question.
Exercise
A DataFrame has 1,000,000 rows and two columns: n (int64) and name (object, holding strings of 6 ASCII characters, each stored as a separate Python object). df.memory_usage(index=False) reports 16,000,000 bytes in total. Roughly what will df.memory_usage(index=False, deep=True).sum() report, and why? (A 6-character ASCII string takes about 55 bytes.)
Show answer
About 71,000,000 bytes. The n column is 8,000,000 bytes either way. The name column is 8,000,000 bytes of pointers in the shallow figure, and deep adds about 1,000,000 × 55 = 55,000,000 bytes for the string objects. That gives 8,000,000 + 8,000,000 + 55,000,000 = 71,000,000 bytes, which is more than four times the shallow total.
Exercise
You convert a column of 1,000,000 integers with some missing values to the nullable Int64 dtype. How many bytes per value does it use, and how does that compare with the same column stored as float64 with NaN?
Show answer
Int64 uses 9 bytes per value: 8 for the int64 data and 1 for the boolean mask that marks missing entries. float64 uses 8 bytes per value. The nullable dtype costs about 12.5% more memory, but it keeps the values as integers and marks missing entries with <NA>.