Sub topic 3
The object dtype: arrays of pointers to Python objects
This chapter assumes you can create a DataFrame and select columns, and that you know basic Python types such as int, float, and str. Familiarity with NumPy arrays helps but is not required. The previous chapter covered NumPy dtypes, where every value has a fixed width and sits in one contiguous block of memory. The object dtype breaks that model, and that explains most of the memory and speed problems people hit with text columns in pandas.
What the object dtype is
A column with dtype int64 is a NumPy array of 8-byte integers. The values themselves are stored in the array. A column with dtype object is a NumPy array of 8-byte pointers (on a 64-bit system). Each pointer refers to a separate Python object stored elsewhere in memory. The array knows where each value lives, but it does not hold the value.
This is the same layout as a Python list. The difference is that the pointers are packed into a NumPy array, so the column still has a length, a shape, and an index alignment like any other column.
When pandas gives you object columns
In pandas 2.x, a column becomes object in these common cases:
- Strings. Unless you request a string dtype, text columns are
object. - Mixed types, such as integers and strings in one column.
- Python objects with no NumPy equivalent, such as lists, dicts,
Decimal, ordatevalues. - Data a parser could not convert to a numeric or datetime type, for example a numeric column with a stray
"n/a"entry.
You can confirm this with the example from the first chapter of this series:
import pandas as pd
df = pd.DataFrame({
"a": [1, 2, 3],
"b": [1.5, 2.5, 3.5],
"c": ["x", "y", "z"],
})
print(df.dtypes)Columns a and b report int64 and float64. Column c reports object.
Note that object is a statement about storage, not about content. An object column can hold only strings, only numbers, or a mixture. The dtype alone does not tell you which. To see what is inside, inspect the values:
import pandas as pd
s = pd.Series(["a", 1, 2.5, None, [1, 2]])
print(s.dtype)
print(s.map(type).value_counts())The map(type) call returns the Python type of each element. This is the quickest way to find the stray value that forced a column into object.
Why object columns cost more memory
An int64 column of one million rows uses about 8 MB: 8 bytes per value. An object column of one million rows uses 8 MB for the pointers, plus the size of every Python object the pointers refer to.
A small Python string is not 4 bytes for "Oslo". CPython attaches a header to every object, including a reference count and a type pointer, plus string-specific fields such as length and hash. A short ASCII string typically takes around 50 bytes in total on a 64-bit build. The exact figure depends on the Python version and on the string's contents.
So a column of short strings can cost roughly 55 to 60 bytes per row, against 8 bytes for an integer.
Shared objects reduce the cost, but not reliably
Python can reuse one object for many pointers. If a column holds the same string object a million times, the pointer array is 8 MB and the string is stored once. This happens, for example, when you build a column with ["Oslo"] * 1_000_000, because list multiplication copies the pointer, not the string.
Data read from a file usually does not behave that way. Parsers may create a fresh string object per cell, although some pandas readers intern repeated values. You cannot rely on sharing, and you cannot see it from the column's dtype. This is one reason the shallow memory figure, covered next, is misleading.
Measuring: shallow versus deep
memory_usage has two modes. The default counts only the memory the column owns directly. For an object column, that means the pointer array. With deep=True, pandas follows the pointers and adds the size of each referenced Python object.
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 frame has 300,000 rows. The default figure is 2,400,000 bytes: 300,000 pointers at 8 bytes each. The deep figure is larger because it adds the string objects. Because the list ["Oslo", "Lima", "Pune"] * 100_000 repeats three string objects, the deep calculation counts each pointer's target. It sums the size of the referenced object once per pointer. So the deep figure can overstate what the process really allocated when many pointers share one object. Treat it as an upper-bound estimate of the column's footprint, and compare it to the actual process memory if the difference matters.
DataFrame.info() also hides this problem by default. It prints a + after the memory figure, such as 2.3+ MB, to signal that object columns were counted shallowly. Passing memory_usage="deep" removes the + and gives the larger number.
| Call | What it counts for an `object` column |
|---|---|
| `df.memory_usage()` | Pointer array only |
| `df.memory_usage(deep=True)` | Pointer array plus each referenced Python object |
| `df.info()` | Pointer array only, with a `+` marker |
| `df.info(memory_usage="deep")` | Pointer array plus referenced objects |
For numeric columns, both modes return the same number, because there is nothing behind the values to follow.
Speed: why object operations are slow
Memory is only part of the cost. NumPy can add two int64 arrays with one compiled loop over contiguous memory. For an object array, there is no such loop. Each element is a Python object, so an operation must follow the pointer and dispatch to that object's own Python method, one element at a time.
You can see the difference with a timing comparison:
import time
import numpy as np
import pandas as pd
n = 1_000_000
ints = pd.Series(np.arange(n, dtype="int64"))
objs = ints.astype("object")
start = time.perf_counter()
ints.sum()
t_int = time.perf_counter() - start
start = time.perf_counter()
objs.sum()
t_obj = time.perf_counter() - start
print(f"int64: {t_int:.5f} s")
print(f"object: {t_obj:.5f} s")Exact timings vary by machine, but the object sum is typically many times slower. Both give the same answer. The only change is how the data is stored.
String methods on object columns, such as .str.upper(), also loop over Python objects. They work, but they run at Python speed, not at compiled-loop speed.
Edge cases and common errors
Numeric data stuck as object
A numeric column becomes object when one entry cannot be parsed, such as "n/a" or "1,234". Arithmetic then fails or behaves like string concatenation. Convert it deliberately:
import pandas as pd
s = pd.Series(["1", "2", "n/a", "4"])
print(s.dtype)
nums = pd.to_numeric(s, errors="coerce")
print(nums.dtype)
print(nums)errors="coerce" turns unparseable entries into NaN, and the column becomes float64. The next chapter explains why NaN forces a float, and how nullable dtypes avoid it.
Missing values inside object columns
An object column can hold None, float("nan"), or pd.NA. isna() recognizes all of them, but the Python objects behind them differ. This matters for code that compares values with ==, because nan == nan is False. Use isna() and notna() rather than equality checks.
Mixed types break sorting
An object column that mixes int and str raises a TypeError when you sort it, because Python 3 does not order those types against each other. Find the offending values with map(type) first.
`astype(str)` does not make a dedicated string column
Calling astype(str) returns an object column of Python strings. It does not switch to a different storage format. It also turns missing values into the literal text "nan" or "None", which isna() no longer detects. Convert with care, and handle missing values first.
Object columns and the block manager
All object columns in a DataFrame are stored together in one object block, just as same-dtype numeric columns share a block. The block holds pointers, so grouping does not remove the per-object cost. A later chapter covers blocks in detail.
What to do about it
Not every object column is a problem. For a small frame the cost is negligible. For large data, three questions guide the choice:
- Are many values repeated? A column of countries or status codes with few distinct values fits the categorical dtype, covered in a later chapter in this series.
- Is the data really numeric or date-like? Convert it with
pd.to_numericorpd.to_datetime, so it uses fixed-width storage. - Is it free text with mostly unique values? Then the strings must be stored somewhere. The later chapters on extension and Arrow-backed dtypes cover alternatives to Python string objects.
Summary
- An
objectcolumn is a NumPy array of 8-byte pointers to Python objects stored elsewhere. - Strings, mixed data, and arbitrary Python objects end up as
objectby default in pandas 2.x. - Shallow
memory_usagecounts only the pointers.deep=Truealso follows them, and may overcount when objects are shared. - Operations loop over Python objects one at a time, so they are much slower than on fixed-width dtypes.
- Detect hidden types with
map(type), and convert numeric-looking data withpd.to_numeric.
Exercise
You load a CSV and find that the column price has dtype object, so df["price"].sum() returns a long concatenated string instead of a number. Write the steps you would take to find the cause and fix the column, and say what dtype you expect afterward if one row contains the text "n/a".
Show answer
First run df["price"].map(type).value_counts() to see which Python types are present, and df.loc[pd.to_numeric(df["price"], errors="coerce").isna(), "price"] to list the entries that fail to parse. Then convert with df["price"] = pd.to_numeric(df["price"], errors="coerce"). The unparseable "n/a" becomes NaN, so the column is float64, and sum() returns a number that skips the missing entry.
Exercise
A DataFrame has one object column of 1,000,000 short strings. df.memory_usage() reports about 8,000,000 bytes for it, but df.memory_usage(deep=True) reports far more. Explain the difference, and say which number is closer to the real cost if every string is a separate Python object.
Show answer
The default figure counts only the pointer array, which is 8 bytes per row. The deep figure also adds the size of each Python string object the pointers refer to. If every string is a separate object, the deep figure is the closer estimate, because each string carries its own object header and contents. If many pointers shared one string object, the deep figure would overcount.