Sub topic 1
Measuring memory: memory_usage(deep=True) and info()
You can't shrink a DataFrame until you know where its memory goes. pandas gives you two tools for this: DataFrame.memory_usage() and DataFrame.info(). Both can report numbers that are too low unless you ask for them carefully. This chapter explains what each tool counts, why the default answer can be wrong by a factor of two or more, and how to build a measurement habit you can reuse in the later chapters.
Prerequisites
This chapter assumes you can:
- Write basic Python and know that a NumPy array stores values of one fixed type in a contiguous block of memory.
- Create a pandas DataFrame, select columns, and call methods on it.
- Recognize the common dtypes
int64,float64, andobject.
The examples assume pandas 2.x with the default object dtype for strings. Newer pandas versions can store strings in a dedicated string dtype. Those columns report different numbers, but the measurement method is the same.
Why measure first
Most memory work goes wrong in one of two ways. You shrink a column that was never the problem, or you trust a number that left out the biggest cost. Measuring first tells you which columns matter and gives you a baseline to compare against after each change.
The workflow for the whole tutorial is:
- Measure the current footprint, per column.
- Pick the columns that dominate.
- Change their dtypes.
- Measure again and check the values.
This chapter covers step 1.
A sample DataFrame
The examples use a DataFrame with 100,000 rows: 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)
print(df.memory_usage())
print(df.memory_usage(deep=True))
print(df.memory_usage(deep=True).sum())df.dtypes shows int64, int64, float64, and object. NumPy's default integer and float types use 8 bytes per value. Each of the three numeric columns therefore needs 100,000 × 8 = 800,000 bytes. That figure doesn't depend on the values, only on the dtype and the row count.
What memory_usage() returns
DataFrame.memory_usage() returns a Series indexed by column name. The values are bytes. It has two parameters that change the answer:
| Parameter | Default | Effect |
|---|---|---|
| `index` | `True` | Adds a row named `Index` for the memory used by the row index. |
| `deep` | `False` | If `True`, inspects the Python objects inside `object` columns instead of counting only their pointers. |
With the defaults, the result for the sample DataFrame is approximately:
| Row | Shallow bytes | Deep bytes |
|---|---|---|
| Index | 132 | 132 |
| user_id | 800,000 | 800,000 |
| age | 800,000 | 800,000 |
| score | 800,000 | 800,000 |
| country | 800,000 | about 5,900,000 |
The Index row is tiny because a default RangeIndex stores only its start, stop, and step. An index of strings or timestamps would cost much more, which is why index=True is the default. Pass index=False when you only care about the columns.
The numeric rows are the same in both columns. The country row is not, and that gap is the main point of this chapter.
Shallow versus deep
An object column is a NumPy array of 8-byte pointers. Each pointer refers to a separate Python object stored elsewhere in memory. The two modes count different things:
- Shallow (
deep=False) counts the pointer array only. Forcountrythat is 100,000 × 8 = 800,000 bytes, as if each string cost 8 bytes. - Deep (
deep=True) also asks Python for the size of every object the pointers refer to, and adds those sizes.
A short ASCII string in CPython occupies about 51 bytes on a typical 64-bit build. You can check this on your machine:
import sys
print(sys.getsizeof("US"))With 100,000 strings at roughly 51 bytes each, the objects add about 5.1 MB on top of the 0.8 MB of pointers. The shallow figure hides more than 80% of the real cost of this column.
The practical rule is to use deep=True whenever a DataFrame has object columns. For a DataFrame of only numeric columns, shallow and deep agree, and the deep scan costs time for nothing.
Reading info()
DataFrame.info() prints a summary: the column names, non-null counts, dtypes, and total memory. By default it gives a cheap estimate.
df.info()
df.info(memory_usage="deep")The last line of the default output looks like this:
memory usage: 3.1+ MBThe + means the number is a lower bound. pandas did not inspect the contents of object columns, so the real figure is higher. With memory_usage="deep" the + disappears and the line reads about 7.9 MB, because the string objects are now included.
Two details are easy to miss:
info()reports in binary units, where 1 MB is 1,024 × 1,024 bytes. The sum ofmemory_usage()is in plain bytes. Divide by1024**2to compare them.- For wide DataFrames,
info()may omit the per-column table. Passverbose=Trueto force it. The per-column memory figures come frommemory_usage(), not frominfo().
You can also make deep reporting the default for info() in a session:
pd.set_option("display.memory_usage", "deep")This option affects only what info() prints. It does not change memory_usage(), which still needs deep=True each time.
A per-column report
Raw bytes are hard to scan. A small helper turns the Series into a table you can sort and read at a glance. It reports both modes side by side and shows each column's share of the total.
def memory_report(df):
shallow = df.memory_usage(index=False)
deep = df.memory_usage(index=False, deep=True)
report = pd.DataFrame({
"dtype": df.dtypes.astype(str),
"shallow_mb": shallow / 1024**2,
"deep_mb": deep / 1024**2,
})
report["share_of_deep"] = report["deep_mb"] / report["deep_mb"].sum()
return report.round(3).sort_values("deep_mb", ascending=False)
print(memory_report(df))For the sample data, country is listed first and accounts for roughly 70% of the deep total. The three numeric columns each hold about 0.76 MB. Without the deep column you would conclude that all four columns cost the same. With it, you know that the string column is where to look first.
Why the numbers are not perfectly exact
The deep figure is a good guide, but it is not an exact count of bytes in RAM. Three things can make it differ from reality.
Shared objects are counted once per reference
deep=True adds up the size of the object behind each pointer. If many pointers refer to the same Python object, that object is counted every time. Here is a column where that happens:
shared = pd.Series(["US"] * 100_000)
print(shared.memory_usage(index=False))
print(shared.memory_usage(index=False, deep=True))The list multiplication creates 100,000 references to a single string object. The real memory is about 0.8 MB of pointers plus one 51-byte string. The deep figure reports about 5.9 MB, because it counts the string 100,000 times.
This does not mean deep is wrong to use. Sharing like this is not guaranteed in general. Strings read from a file or built by other operations are usually separate objects, as in the sample DataFrame. Treat the deep number as the cost you should expect for typical data, and as an upper bound when the strings are known to be shared. It is also what you will need once the data is copied, pickled, or written out, since those operations expand shared references.
Memory the DataFrame does not own
memory_usage() describes the column data. It does not include:
- The Python process baseline, the pandas library itself, or other variables in your session.
- Temporary copies made during operations. A
merge,sort_values, orastypecan briefly hold the old and new data at once, so peak usage during processing can be well above the final DataFrame size. - Views. Two DataFrames that share the same underlying array each report the full size, so adding their reports double counts.
If you need the process total, measure it with an operating system tool or a library such as psutil. Use memory_usage() to compare one DataFrame against another version of itself.
Platform and version differences
String object sizes depend on the Python version and build. Non-ASCII text takes more bytes per character than ASCII. Your totals may differ from the figures in this chapter by a few percent. What matters is the ratio between the columns and the before-and-after comparison on your own machine.
Common errors
- Reading the default total as the real size.
df.memory_usage().sum()on a DataFrame with strings can understate the footprint several times over. Always passdeep=Truewhenobjectcolumns exist. - Expecting
info()to be exact. A+after the number means a lower bound. Usememory_usage="deep"before deciding anything. - Mixing units.
info()shows binary megabytes andmemory_usage()shows bytes. Convert before comparing. - Forgetting the index. On a DataFrame with a string or datetime index, leaving
index=Trueis correct and matters. If you want column-only figures, sayindex=Falseexplicitly. - Measuring after the fact only. Taking a baseline before you change dtypes is what lets you prove a saving later.
Measuring on a sample
If the full DataFrame is too large to scan comfortably, measure a random sample and scale up. The column dtypes and string lengths of a sample are usually representative.
sample = df.sample(10_000, random_state=0)
per_row = sample.memory_usage(index=False, deep=True).sum() / len(sample)
print(round(per_row * len(df) / 1024**2, 2), "MB estimated")The estimate will be close to the real deep total for this data. It can be off when a few rows hold unusually long strings, so check it against the full measurement at least once.
Exercise
A DataFrame has 1,000,000 rows and one object column of two-letter country codes. df.memoryusage().sum() reports about 8 MB for that column, but df.memoryusage(deep=True).sum() reports about 59 MB. Where does the extra memory come from, and which number should you use to decide whether to convert the column?
Show answer
The shallow figure counts only the array of 8-byte pointers (1,000,000 × 8 = 8 MB). Each pointer refers to a separate Python string object of roughly 51 bytes, which adds about 51 MB that shallow mode does not inspect. Use the deep figure, because it includes the string objects you would actually save by converting the column.
Exercise
You call df.info() and the last line reads "memory usage: 12.4+ MB". What does the "+" mean, and what call gives you a figure without it?
Show answer
The "+" means the figure is a lower bound, because pandas did not inspect the Python objects inside object columns. Calling df.info(memory_usage="deep") counts those objects and removes the "+".