Sub topic 7
Measuring memory: shallow versus deep
This chapter assumes you can create a DataFrame, select columns, and know that each column has a dtype (a fixed type for all its values). You should also know that an object column holds pointers to Python objects. The goal is to read pandas memory numbers correctly, because the default numbers can be badly wrong for string columns.
What memory_usage reports
DataFrame.memory_usage() returns a Series with the bytes used by each column. By default it counts only the array that the column owns. For a numeric column, that array holds the values, so the number is accurate. For an object column, the array holds 8-byte pointers (on a 64-bit build). The Python string objects that the pointers refer to are not counted.
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima", "Pune"] * 100_000})
print(df.memory_usage(index=False)["city"])
print(df.memory_usage(index=False, deep=True)["city"])
df.info(memory_usage="deep")The first number is 300,000 rows times 8 bytes, which is 2,400,000. The second number is much larger, because deep=True follows each pointer and adds the size of the Python object it finds. The exact deep figure depends on your Python version.
Shallow versus deep
The two modes answer different questions.
| Mode | Call | What it counts | Cost |
|---|---|---|---|
| Shallow | `memory_usage()` | Column arrays only. For `object`, just the pointers. | Instant |
| Deep | `memory_usage(deep=True)` | Arrays plus the Python objects that `object` columns point to. | Walks every object, so it is slower on large frames |
Use deep when you want to know how much RAM a frame really needs. Use shallow when you only need a fast estimate for numeric data.
Because the diagram type must be fenced as specified, here is the model in the required form.
Reading info()
df.info() prints dtypes, non-null counts, and a memory total. By default it adds a + after the memory figure when the frame has object columns, as in 7.2+ MB. The plus sign means the number is a lower bound. Pass memory_usage="deep" to get the real total.
You can also set this globally with the display.memory_usage option, but passing the argument per call is clearer.
The index counts too
memory_usage() includes the index as its own row by default. A RangeIndex is stored as start, stop, and step, so it uses a fixed small amount. Other index types store a full array. Pass index=False when you want to compare columns only, as the examples above do.
Common errors
- Trusting the shallow number for strings. A frame of 10 million short strings can look like 80 MB shallow and use many times that deep.
- Adding the index by accident. Totals from
memory_usage().sum()include the index row. Compare like with like. - Expecting process memory to match. These figures cover the frame's data. Your process also holds temporary copies, Python overhead, and memory the allocator has not returned to the operating system.
- Measuring a slice and generalizing. Deep measurement on a small sample can mislead if string lengths vary. Measure a representative sample or the whole column.
Comparing before and after
A measurement is most useful as a comparison. The next chapters change a column's dtype, so get in the habit of measuring the same column in both forms.
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima", "Pune"] * 100_000})
before = df["city"].memory_usage(index=False, deep=True)
after = df["city"].astype("category").memory_usage(index=False, deep=True)
print(f"object: {before:,} bytes")
print(f"category: {after:,} bytes")
print(f"ratio: {before / after:.0f}x")Always pass deep=True on both sides. Comparing a shallow object figure with a deep category figure, or the reverse, gives a meaningless ratio.
Exercise
A DataFrame has one int64 column and one object column of strings, each with 1,000,000 rows. df.memory_usage(index=False) reports 8,000,000 bytes for both columns. Why is that figure misleading, and what call gives a better estimate of RAM use?
Show answer
With the default shallow mode, the object column is counted as 1,000,000 pointers of 8 bytes each, and the string objects themselves are left out. The real memory is higher. Call df.memory_usage(index=False, deep=True), or df.info(memory_usage="deep"), to include the Python string objects.
Exercise
What does the + in an info() memory line such as 22.9+ MB tell you?
Show answer
The frame has object columns and the figure is a lower bound, because pandas did not follow the pointers. Use df.info(memory_usage="deep") for the full total.