Sub topic 10
Checking memory use with info
This chapter assumes you can read the basic df.info() output: the index range, the non-null counts, and the dtypes. You should also be comfortable with pandas dtypes such as int64, float64, and object. Here we focus on the last line of that output, the memory figure, and on how to make it accurate.
Where the memory figure appears
info() ends with a line like memory usage: ... bytes. It tells you roughly how much RAM the DataFrame occupies. Check it before you load more data, copy a frame, or run an operation that duplicates it.
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()The memory line may end with a plus sign, for example 288.0+ bytes. The plus sign means the number is a lower bound. That happens when the frame has object columns, which here are name and city.
Why the default number is a lower bound
A numeric column stores its values in one block of fixed-size slots. Its size is exact: salary holds 5 values of 8 bytes each.
An object column stores pointers to Python objects, such as strings, that live elsewhere in memory. By default, info() counts only the pointers and not the strings they point to. Counting the strings would mean visiting every value, which is slow on a large frame.
Asking for the real figure with deep
Pass memory_usage="deep" to make pandas inspect the objects themselves.
df.info(memory_usage="deep")The plus sign disappears and the total grows. On a tiny frame the gap is small. On millions of rows with text columns, the deep figure can be several times larger than the default one.
You can also turn the line off with memory_usage=False. This is useful if you only want the dtypes.
Seeing which column costs the most
info() gives one total. To find the expensive column, use DataFrame.memory_usage. It returns a Series of bytes per column, and it includes the index by default.
print(df.memory_usage())
print(df.memory_usage(deep=True))
print(df.memory_usage(deep=True).sum())A worked example: shrinking a text column
A column with few distinct values and many rows is a good candidate for the category dtype. A category column stores each distinct string once and keeps a small integer code per row.
big = pd.DataFrame({
"city": np.random.choice(["Lima", "Oslo", "Pune"], size=100_000),
"salary": np.random.randint(40_000, 90_000, size=100_000),
})
before = big.memory_usage(deep=True)
big["city"] = big["city"].astype("category")
after = big.memory_usage(deep=True)
print(before["city"], after["city"])
big.info(memory_usage="deep")The city column drops from several megabytes to a few hundred kilobytes. The exact numbers depend on your pandas version and platform, but the reduction is large.
Common mistakes
- Treating the default figure as exact when the frame has
objectcolumns. - Using
deepon a very large frame without expecting a delay. Measuring every object takes time. - Forgetting that the index uses memory too.
memory_usage()includes it unless you passindex=False. - Converting to
categorywhen most values are unique. Then there is no saving, and the column can even grow.
Exercise
A frame has an int64 column and a string column of 1,000,000 rows. df.info() reports memory usage: 15.3+ MB. What does the plus sign mean, how do you get the accurate figure, and why is it larger?
Show answer
The plus sign means the figure is a lower bound, because the string column is an object column and only its pointers were counted. Call df.info(memory_usage="deep") or df.memory_usage(deep=True).sum(). The result is larger because pandas then also measures the memory used by each Python string.
Exercise
Which call shows memory use per column, including the index, and how would you exclude the index?
Show answer
df.memory_usage(deep=True) returns bytes per column and includes the index as its own row. Pass index=False to leave the index out.