Sub topic 5
Why object columns of strings use so much memory
This chapter explains where the memory goes when a pandas column holds Python strings. It assumes you know how to create and index DataFrames, that you have used memory_usage(deep=True) from the earlier chapter on measuring memory, and that you know what int64, float64 and object mean. The goal is a mechanism you can use to predict a column's footprint before you measure it.
What an object column stores
A numeric column such as int64 is one contiguous block of memory. Each value takes a fixed number of bytes, so 100,000 rows of int64 take exactly 800,000 bytes.
An object column cannot work that way, because strings vary in length. pandas stores an array of 8-byte pointers (on a 64-bit build). Each pointer refers to a separate Python object somewhere else on the heap. The column therefore has two parts:
- The pointer array, which is 8 bytes per row.
- The string objects, each a full Python
strwith its own header and character data.
The third row repeats the value 'US', yet it can point to its own object. That is the central cost: repetition in the data is not automatically shared in memory.
How big is one Python string?
CPython stores every str as an object with a fixed header. That header holds a reference count, a type pointer, the length, a cached hash and flags. For an ASCII string the header takes about 49 bytes, and then the characters follow at 1 byte each. sys.getsizeof reports this.
import sys
for s in ["", "US", "user_123", "a" * 100]:
print(repr(s[:10]), sys.getsizeof(s))On a typical 64-bit CPython 3.x the output is 49, 51, 57 and 149. The exact numbers can differ slightly between Python versions, but the shape does not change: a fixed overhead of roughly 49 bytes, plus the characters.
Strings with non-ASCII characters cost more per character. CPython picks 1, 2 or 4 bytes per character depending on the widest character in the string. The header is also slightly larger. A string of emoji uses 4 bytes per character.
Now put this together for one row holding a two-letter country code:
- 8 bytes for the pointer.
- 51 bytes for the string object.
- Total: about 59 bytes for information that fits in 1 byte if you number the five possible countries.
That ratio, roughly 59 to 1, is why string columns often dominate a DataFrame's memory.
Shallow versus deep measurement
memory_usage() without deep=True counts only the pointer array. It has no way to know what the pointers lead to without visiting each one. With deep=True, pandas calls sys.getsizeof on every element and adds the results.
import sys
import pandas as pd
n = 100_000
labels = [f"user_{i % 5}" for i in range(n)]
s = pd.Series(labels, dtype=object)
shallow = s.memory_usage(index=False)
deep = s.memory_usage(index=False, deep=True)
expected = 8 * n + sum(sys.getsizeof(x) for x in labels)
print(shallow)
print(deep)
print(deep == expected)The shallow figure is 800,000 bytes, exactly 8 bytes per row. The deep figure is 6,300,000 bytes, because each string user_0 through user_4 is 55 bytes. The comparison with expected prints True, which confirms that deep measurement is pointers plus the sum of getsizeof over the elements.
The shallow number understates the column by a factor of about 8. Reporting tools, dashboards and quick df.info() calls often show the shallow number, so a DataFrame that looks like 10 MB can need far more.
Repetition is not sharing
In the example above, the list comprehension builds a new string for every row. Each f"user_{i % 5}" call creates a fresh object, even though only five distinct values exist. You can check this by counting distinct object identities.
import pandas as pd
n = 100_000
labels = [f"user_{i % 5}" for i in range(n)]
distinct_objects = pd.Series(labels, dtype=object)
shared_value = "user_0"
one_object = pd.Series([shared_value] * n, dtype=object)
print(len({id(x) for x in distinct_objects}))
print(len({id(x) for x in one_object}))
print(distinct_objects.memory_usage(index=False, deep=True))
print(one_object.memory_usage(index=False, deep=True))The first count is 100,000, so every row has its own object. The second count is 1, because [shared_value] * n repeats the same reference n times.
Both deep totals come out at 6,300,000 bytes. The second column really occupies only about 800,000 bytes, which is the pointer array plus one 55-byte string, but deep=True reports 6,300,000 anyway. The reason is that deep measurement sums getsizeof per element and does not notice that elements are the same object.
This has two consequences:
- Deep measurement is an upper bound when strings are shared. It is accurate when each row has its own string object, which is the usual case for data read from files or built by string operations.
- Sharing can happen without you asking for it. CPython caches single-character Latin-1 strings, and
sys.internor some parsers can reuse objects. If you see the same strings reused, the true footprint can be lower than the deep figure.
Where else the overhead comes from
The pointer array and string objects are the main costs, but a few other effects matter in practice.
- Mixed contents. An
objectcolumn can hold anything: strings, numbers,None, lists. Deep measurement counts each element's owngetsizeof. For a list, that excludes the items inside it, so deep measurement undercounts nested containers. - Missing values. A missing value in an object column is usually
np.nan,Noneorpd.NA. They are single shared objects, so the deep figure counts them once per row (about 24 bytes for a floatnan) although the real cost is only the pointer. - Temporary copies. Reading a CSV, splitting strings or applying
strmethods creates new string objects. Peak memory during a transformation can be well above the final footprint, which is one reason to set dtypes at load time (covered in a later chapter). - Pandas version. In pandas 3.0 and later, string columns infer a dedicated string dtype by default, and with PyArrow installed the data is stored in Arrow's compact layout, with no per-row Python object. In earlier versions, plain string columns are
objectunless you ask for"string"or"string[pyarrow]". Checkdf.dtypesbefore assuming your column has the object layout described here.
What this means for repeated values
Because the cost is per row and not per distinct value, a column with five distinct strings in 100,000 rows costs as much as one with 100,000 distinct strings of the same length. The first column carries the same information in far less space, if only it were stored differently.
The category dtype does that. It stores each distinct string once and keeps a small integer code per row. A quick preview shows the size of the effect.
import pandas as pd
n = 100_000
labels = [f"user_{i % 5}" for i in range(n)]
as_object = pd.Series(labels, dtype=object)
as_category = as_object.astype("category")
print(as_object.memory_usage(index=False, deep=True))
print(as_category.memory_usage(index=False, deep=True))
print(as_category.cat.codes.dtype)The object column reports 6,300,000 bytes. The category column reports a little over 100,000 bytes: 1 byte per row for the int8 codes, plus a few hundred bytes for the five stored strings. That is a reduction of about 98%. The next chapters explain how the conversion works, when it pays off, and which operations behave differently afterward.
Estimating before you measure
You can predict an object column's deep size from three inputs: row count, average string length, and whether each row owns its string.
| Component | Cost per row | Notes |
|---|---|---|
| Pointer in the array | 8 bytes | Always present, counted by shallow measurement |
| String header | about 49 bytes | ASCII strings on 64-bit CPython; slightly more for non-ASCII |
| Characters | 1 byte each for ASCII | 2 or 4 bytes each if the string holds wider characters |
For ASCII strings with an average length of L, the estimate is rows * (8 + 49 + L) bytes. Compare that with an int8 code column at rows * 1 byte to see the best case for conversion.
Common mistakes
- Reading the shallow memory number and concluding that a string column is cheap.
- Assuming that repeated values share one object. They do only if your code makes them share one.
- Comparing a shallow measurement before a change with a deep measurement after it.
- Applying the object-layout estimate to a pandas 3
strcolumn or astring[pyarrow]column, which store text differently.
Exercise
A DataFrame has 1,000,000 rows. One column holds ASCII strings that are 10 characters long, and each row owns its own string object. Estimate the column's size with deep=True on 64-bit CPython, in bytes. How much of that does a shallow measurement report?
Show answer
Per row: 8 bytes for the pointer plus about 49 bytes of header plus 10 bytes of characters, which is 67 bytes. For 1,000,000 rows the deep size is about 67,000,000 bytes (67 MB). A shallow measurement reports only the pointer array, 8,000,000 bytes, which is about 12% of the real figure.
Exercise
You build a Series with pd.Series(["US"] * 100_000, dtype=object). Why does memory_usage(deep=True) report about 5.9 million bytes even though the column holds a single string object, and what does that tell you about trusting the figure?
Show answer
Deep measurement sums sys.getsizeof over every element (59 bytes per row here, counting the 8-byte pointer and the 51-byte string), and it does not detect that all elements are the same object. The real footprint is about 800,000 bytes for the pointer array plus one 51-byte string. The deep figure is an upper bound when objects are shared, so use it for before-and-after comparisons and check process memory for exact accounting.