Sub topic 10
Checking memory use with info
This chapter assumes you can read the basic output of DataFrame.info() (index range, column names, non-null counts, dtypes) and know what a dtype is. It covers the last line of that output, the memory figure, and how to turn it into a decision about your data.
Why memory belongs in a first look
A DataFrame lives entirely in RAM. A file that is 200 MB on disk can take more or less memory once loaded, depending on its dtypes. If you learn this early, you can pick better dtypes before you hit a MemoryError or a slow notebook.
info() reports memory in its last line. The number can mislead if you don't know how it is computed. The default figure is a lower bound for some columns, and that is the main point of this chapter.
The memory line in info
Start with the small DataFrame used throughout this tutorial.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cleo", "Dev", "Eli"],
"age": [34, 28, np.nan, 45, 39],
"city": ["Lima", "Oslo", "Lima", "Pune", "Oslo"],
"salary": [52000, 48000, 61000, 75000, 58000],
})
df.info()
df.info(memory_usage="deep")info() writes straight to the console and returns None, so you don't wrap it in print. The first call ends with a line like memory usage: 288.0+ bytes. The second ends with a larger number and no plus sign. The exact values depend on your pandas version and platform, but the shape of the result is stable:
- The first figure carries a
+. - The deep figure has no
+. - The deep figure is larger, because this DataFrame has text columns.
What the plus sign means
The + is a warning that the number is a lower bound. By default, info() counts only the memory of the arrays that pandas holds for each column. It does not look inside the individual Python objects those arrays point to.
Numeric columns are simple. An int64 column with 5 rows takes 5 × 8 = 40 bytes, and nothing else is hidden. An object column (the usual dtype for text in older pandas versions) is different. Its array holds one 8-byte pointer per row, and each pointer refers to a separate Python str object somewhere else in memory. The default count includes the pointers but not the strings.
| Column dtype | Default (shallow) count | Deep count |
|---|---|---|
| `int64`, `float64`, `bool` | Exact | Same as shallow |
| `category` | Exact (codes plus the category labels) | Same as shallow |
| `object` | Pointers only (8 bytes per row) | Pointers plus every Python object |
When info() sees any object column and you have not asked for deep inspection, it adds the +. If there are no object columns, no + appears, because the figure is already exact.
Shallow versus deep: what it costs
Deep inspection has a price. For object columns, pandas must visit each element and ask Python how large it is. On a few thousand rows you won't notice. On tens of millions of rows of text, memory_usage="deep" can take noticeable time. The shallow default is cheap because it only reads array sizes.
A working rule:
- Use the default for a quick look, and treat a
+as "at least this much". - Use
"deep"when you need to size a machine, compare two representations, or check whether a text column is the problem.
Python strings also have overhead. A short ASCII str takes roughly 50 bytes or more in CPython, much more than its characters. A column of one million short names can therefore take around 50 MB in deep mode, against 8 MB in shallow mode.
Per-column detail with memory_usage
info() gives one total. To see which column is responsible, use the DataFrame.memory_usage method. It returns a Series of bytes, indexed by column name, with the index itself listed first.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cleo", "Dev", "Eli"],
"age": [34, 28, np.nan, 45, 39],
"city": ["Lima", "Oslo", "Lima", "Pune", "Oslo"],
"salary": [52000, 48000, 61000, 75000, 58000],
})
print(df.memory_usage())
print(df.memory_usage(deep=True))
print(df.memory_usage(deep=True).sum())
print(df.memory_usage(index=False, deep=True))Things to notice in the output:
- The
Indexrow is included by default. Passindex=Falseto leave it out. age,salaryand any other numeric columns are the same in both calls.nameandcitygrow whendeep=True.- The
.sum()of the deep Series is the same total thatinfo(memory_usage="deep")reports.
Note the argument spelling. info() takes memory_usage="deep", while memory_usage() takes deep=True. Mixing them up raises a TypeError or silently does nothing useful.
Controlling the memory line
You have three controls over what info() prints.
df.info(memory_usage=False)removes the memory line. This is handy for very wide frames, where you want only dtypes and counts.df.info(memory_usage="deep")forces the exact count.pd.set_option("display.memory_usage", "deep")makes deep the default for the session. The same option acceptsTrue,False, or"deep".
Two related arguments are worth knowing because they change how much info() prints, not how it measures memory. show_counts=False hides the non-null counts, and verbose=False collapses the per-column table into a short summary. On a frame with hundreds of columns, verbose=False still gives you the dtype tally and the memory line:
import numpy as np
import pandas as pd
wide = pd.DataFrame(np.zeros((1000, 300)), columns=[f"c{i}" for i in range(300)])
wide.info(verbose=False)If you need the report as a string, for logging, pass a buffer. info() itself still returns None.
import io
import pandas as pd
df = pd.DataFrame({"city": ["Lima", "Oslo", "Lima"], "n": [1, 2, 3]})
buffer = io.StringIO()
df.info(buf=buffer, memory_usage="deep")
report = buffer.getvalue()
print(report.splitlines()[-1])The last line of the report is the memory line, so the script prints it alone.
Using the numbers: shrinking a DataFrame
The memory figure is most useful when you act on it. The next example builds 100,000 rows with a repetitive text column and compares the memory before and after changing dtypes.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 100_000
big = pd.DataFrame({
"city": rng.choice(["Lima", "Oslo", "Pune", "Kyiv"], size=n),
"age": rng.integers(18, 80, size=n),
"salary": rng.normal(60000, 12000, size=n).round(0),
})
before = big.memory_usage(deep=True)
print(before)
print("total before:", before.sum())
small = big.astype({
"city": "category",
"age": "int8",
"salary": "float32",
})
after = small.memory_usage(deep=True)
print(after)
print("total after:", after.sum())
print("ratio:", round(after.sum() / before.sum(), 3))
small.info(memory_usage="deep")What to expect, approximately:
ageasint64costs 800,000 bytes (100,000 × 8). Asint8it costs 100,000 bytes.salaryasfloat64costs 800,000 bytes. Asfloat32it costs 400,000 bytes.cityasobjectis the largest by far in deep mode, because each row points to a string object. Ascategory, pandas stores one small integer code per row plus the four labels once, so it costs about 100,000 bytes plus a small constant.- The total falls to a fraction of the original. The text column accounts for most of the saving.
Each change has a condition:
int8holds only -128 to 127. The ages here are 18 to 79, so they fit. A value outside the range would overflow or raise an error, depending on how you convert it.float32keeps about 7 significant digits. That is fine for these rounded salaries but not for values that need full precision.categorypays off when the number of distinct values is small relative to the number of rows. For a column where almost every value is unique, such as an ID, it can use more memory thanobject.
A safer way to pick integer sizes is pd.to_numeric(series, downcast="integer"), which chooses the smallest type that holds the actual values.
Common errors and gotchas
- Treating the plus-sign number as the true size. For object columns the real footprint can be several times larger. Re-run with
"deep"before drawing conclusions. - Comparing shallow and deep figures. When you compare two versions of a DataFrame, use the same mode for both. A
categorycolumn looks cheap in either mode, but anobjectcolumn looks cheap only in shallow mode. - Forgetting the index. The index counts toward the total. A
RangeIndexis tiny, but an index of strings or timestamps can be large. Usememory_usage(index=False)when you want to compare columns alone. - Expecting memory to match file size. A CSV stores numbers as text. After loading,
int64always takes 8 bytes per value whether the text was1or1000000. - Dtype changes across pandas versions. Newer pandas releases can infer a dedicated string dtype for text instead of
object. If your text column shows a dtype other thanobject, the+rules above may not apply to it, and the memory figures may differ from those described here. Always read the dtype column in the sameinfo()output. - Peak memory is higher than the figure. The number describes the finished DataFrame. Loading a file, or running
astype, can briefly hold both the old and new data. Plan for a multiple of the reported size.
Where this fits in the first-look routine
Memory is the last thing you read from info(), after dtypes and non-null counts. A text column stored as object points to two follow-ups: check whether it should be category, and check whether it hides numbers stored as text. Both questions come from reading the dtype column and the memory line together, and the next chapters build on that.
Exercise
A DataFrame with one million rows has a text column country (about 200 distinct values, dtype object) and an integer column year (values 1990 to 2024, dtype int64). df.info() reports memory usage: 15.3+ MB. (a) Why does the number have a plus sign? (b) How do you get the exact total? (c) Which two dtype changes would you try, and why are they safe for these columns?
Show answer
(a) The frame has an object column, and the default count includes only the 8-byte pointers for it, not the Python string objects they refer to, so 15.3 MB is a lower bound. (b) Call df.info(memory_usage="deep"), or df.memory_usage(deep=True).sum(). (c) Convert country to category, because only about 200 distinct values repeat across a million rows, so pandas stores small integer codes plus 200 labels. Convert year to int16, because 1990 to 2024 fits easily in the range -32,768 to 32,767. Confirm the range with describe() first.
Exercise
You run small = big.astype({"city": "category"}) on a frame where city has 99,000 distinct values in 100,000 rows. Memory in deep mode barely drops, or even rises. Why, and how would you check before converting?
Show answer
A category column stores one integer code per row plus one copy of every distinct label. With almost every value unique, the labels take about as much space as the original strings, and the codes are extra. Check df["city"].nunique() against len(df) before converting, and compare df.memory_usage(deep=True) before and after on a sample.