Sub topic 3
The object dtype: arrays of pointers to Python objects
This chapter assumes you can create a DataFrame and select columns. It also assumes you know the basic Python types int, float, and str. In the previous chapter, a NumPy dtype such as int64 meant fixed-width values packed side by side in one contiguous array. The object dtype breaks that model.
What object means
A column with dtype object is a NumPy array whose slots each hold a pointer. Each pointer is 8 bytes on a 64-bit build, and it refers to an ordinary Python object stored elsewhere in memory. The array itself knows nothing about what those objects are.
Pandas 2.x uses object for text by default. You can confirm this directly:
import sys
import pandas as pd
s = pd.Series(["Oslo", "Lima", "Pune"])
print(s.dtype) # object
print(type(s.iloc[0])) # <class 'str'>
print(s.to_numpy().itemsize) # 8 on a 64-bit build: the pointer size
print(sys.getsizeof("Oslo")) # size of one Python str objectitemsize reports only the pointer. sys.getsizeof shows that each short string costs far more than 8 bytes: CPython adds roughly 49 bytes of per-object overhead to the characters.
Why object columns are slow and large
- Memory. You pay for the pointer array and for every Python object it refers to.
- Speed. Operations cannot run as tight loops over raw machine values. Each element must be looked up through its pointer, and its Python type must be checked.
- Locality. The objects are scattered across the heap, so the CPU cache works poorly.
Compare summing an int64 column, which is one fast loop over contiguous memory, with summing an object column of Python ints. The second case calls Python-level addition for each element.
Mixed types in one column
Because the array only stores pointers, one column can hold values of different Python types.
import pandas as pd
mixed = pd.Series([1, "two", 3.0, None])
print(mixed.dtype)
print(mixed.map(type).tolist())The output shows object, then a list of four different types: int, str, float, and NoneType. Pandas does not stop you from doing this. That flexibility causes the most common errors with object columns.
Common errors
- Numbers stored as text. A CSV column with one stray entry such as
"n/a"loads asobject, and every number in it is a string. Arithmetic then fails with aTypeError, or it concatenates strings instead of adding numbers. - Silent mixed types. Sorting or comparing a column that mixes
intandstrraisesTypeError. Aggregations may also behave differently from what you expect. - Assuming object means string. An object column may hold dates, lists, dicts, or any other Python object.
To find and repair the first problem, convert with errors="coerce", which turns unparseable entries into missing values:
import pandas as pd
raw = pd.Series(["1", "2", "x", "4"])
print(raw.dtype)
clean = pd.to_numeric(raw, errors="coerce")
print(clean.dtype)
print(clean)The result is float64, with NaN where "x" was. The float dtype is a consequence of the missing value, which the next chapter covers.
Seeing the cost
memory_usage() counts only the pointer array by default. Passing deep=True follows the pointers and adds the size of each Python object. The "Measuring memory" chapter covers this in detail. For now, a single comparison shows the gap:
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima", "Pune"] * 100_000})
print(df["city"].memory_usage(index=False))
print(df["city"].memory_usage(index=False, deep=True))The first number is 2,400,000 bytes, which is 300,000 pointers of 8 bytes each. The second is several times larger. Pandas adds up each object's size separately, even when many pointers refer to the same string object, so the deep figure is an upper estimate.
Exercise
A column loaded from a CSV has dtype object, and df["price"].sum() returns a long string such as "12.50" and "8.00" joined together. What is the likely cause, and how do you fix it?
Show answer
The column holds strings, probably because at least one entry is not a valid number, which forced the whole column to object. Summing strings concatenates them. Fix it with pd.to_numeric(df["price"], errors="coerce"), then inspect the rows that became NaN to see which entries were invalid.