Sub topic 1
Why Text in object Columns Is a Problem
Pandas has stored text in object columns since its first releases. An object column holds any Python value, so it holds text, but it also holds a lot of other things. This chapter explains what that costs you in correctness, clarity, and memory. The costs are the reason the dedicated string dtype exists, which the next chapters cover.
Prerequisites
This chapter assumes you can do the following:
- Work with Python strings and know basic regular expression syntax.
- Create and index pandas Series and DataFrames.
- Explain what a dtype is in pandas and NumPy, for example why
int64is stored differently fromfloat64.
The examples create their object columns with dtype=object explicitly. Pandas 3 changes what an unlabeled list of strings becomes (see the callout below), and the explicit dtype keeps the examples consistent across versions.
What an object column is
A NumPy array of int64 values is a block of 8-byte integers. An object array is different. It is a block of 8-byte pointers, and each pointer refers to a full Python object stored elsewhere in memory. Pandas does not constrain what those objects are.
import pandas as pd
s = pd.Series(["apple", "banana", None, 42, 3.5], dtype=object)
print(s.dtype)
print(s.map(type).tolist())The first line prints object. The second shows five different Python types in one column: str, str, NoneType, int, and float. Pandas accepted all of them without complaint.
This design is flexible, but three problems follow from it:
- The dtype does not tell you the column contains text.
- Missing values can take several forms.
- Every element is a separate Python object, which costs memory and speed.
The dtype does not tell you the column is text
object is also the dtype for lists, dicts, dates stored as Python objects, decimals, and any mix of these. When you see object in df.dtypes, you know only that pandas could not find a more specific NumPy dtype.
You can ask pandas to inspect the contents with pd.api.types.infer_dtype.
import pandas as pd
text = pd.Series(["a", "b", None], dtype=object)
mixed = pd.Series(["a", 1, None], dtype=object)
nested = pd.Series([[1, 2], {"k": 1}], dtype=object)
for s in (text, mixed, nested):
print(s.dtype, pd.api.types.infer_dtype(s))All three Series report object as the dtype. The inferred types differ: string, mixed-integer, and mixed. The inference scans every element, so it costs time proportional to the column length, and it describes the current contents only. Nothing stops a later assignment from adding an integer to the text Series. The check you ran earlier no longer applies after that assignment.
In practice this means a schema check such as "column name has dtype object" proves very little. Mixed values often arrive from real data:
- A CSV column where most rows are text but a few were parsed as numbers.
- A merge that leaves some cells as
NaNfloats. - A function that returns
Nonefor some inputs and an integer code for others.
Each of these produces an object column that looks like text in a quick df.head() and misbehaves later.
Missing values come in several forms
In an object column, "missing" has no single representation. Three different values commonly appear:
None, the Python null object.float("nan"), which isnumpy.nan, the floating-point not-a-number value.pd.NA, the newer pandas missing-value marker.
import pandas as pd
s = pd.Series(["a", None, float("nan"), pd.NA], dtype=object)
print(s.isna().tolist())
print(s.map(repr).tolist())isna() returns [False, True, True, True], so pandas recognizes all three as missing. The repr output shows they are three different objects: 'None', 'nan', and '<NA>'. The columns' behavior depends on which one you have. nan != nan is True in Python, while None == None is True. pd.NA raises an error if you use it in a boolean context such as an if statement. Code that tests for missing values with x is None or x == x catches some of these and misses others.
The safe habit is to use isna() and notna() and never compare against a specific missing marker. This works, but it relies on discipline, because the column itself does not enforce one representation.
The .str accessor hides problems
The .str accessor applies string methods to a Series. On an object column it accepts almost any content, including a mix of strings and other objects. For non-string elements it quietly produces NaN instead of raising an error.
import pandas as pd
s = pd.Series(["ab", "cde", 42], dtype=object)
print(s.str.len())The output is 2.0, 3.0, NaN. The integer 42 is not a string, so its length is NaN. No warning is raised. The result dtype is float64, because integer lengths and NaN can only share a column as floats. The caller asked for the length of each string and got a float column with a gap in it.
The accessor has one limit. If a column contains no strings at all, for example only integers, .str raises an AttributeError ("Can only use .str accessor with string values!"). A single string in the column is enough to make the accessor available again. Whether the accessor works therefore depends on the data in the column and not on its declared type.
Boolean results that cannot filter
The most common way object columns surprise people is a boolean mask that contains missing values.
import pandas as pd
s = pd.Series(["alpha", None, "gamma"], dtype=object)
mask = s.str.contains("a")
print(mask.dtype)
print(mask.tolist())
try:
print(s[mask])
except ValueError as e:
print("ValueError:", e)mask.dtype is object, and the list is [True, nan, True]. A boolean mask with NaN in it is not a valid indexer, so s[mask] raises a ValueError about masking with non-boolean values containing NA or NaN. The usual fix is na=False:
print(s[s.str.contains("a", na=False)])That works, but you must remember the argument every time you filter. The deeper issue is that the result is an object Series holding Python bool values and NaN, not a real boolean column. It cannot be used in & and | expressions the way you would expect, and it uses far more memory than it needs to.
The same inconsistency affects other results. A method that returns integers gives float64 once a missing value appears. A method that returns booleans gives object. The result dtype depends on whether the input contained missing values.
Memory and speed
Every element in an object column is a pointer plus a full Python object. A short Python string takes roughly 50 bytes or more once you include its header, even if the text itself is a few characters. A fixed-width or Arrow-style layout stores the same text in a few bytes per element.
By default, memory_usage() reports only the pointer array. Add deep=True to include the objects that the pointers refer to.
import pandas as pd
values = ["red", "green", "blue"] * 1000
s = pd.Series(values, dtype=object)
print(s.memory_usage())
print(s.memory_usage(deep=True))The first number is about 8 bytes per element plus the index. The second is several times larger, because it adds the size of each string object. The default figure hides most of the real cost, so measure with deep=True when you compare text representations. The exact numbers vary by Python version and platform.
Speed has a related cause. A vectorized numeric operation on int64 runs in compiled C over contiguous memory. Operations on an object column typically loop over the pointers, call a Python function on each object, and check its type. The .str methods on object columns are loops of this kind. Their speed is acceptable for small data, and it becomes a bottleneck on millions of rows.
Summary of the costs
| Concern | Text in an `object` column | What you want |
|---|---|---|
| Declared type | `object`, which could be anything | A dtype that means "text" |
| Missing values | `None`, `NaN`, or `pd.NA` | One consistent marker |
| Non-string values | Accepted silently on assignment | Rejected at assignment |
| `.str` on non-strings | Silent `NaN` | A clear error or a defined result |
| Boolean results | `object` with `NaN`, unusable as a mask | A real nullable boolean |
| Memory | Pointer plus full Python object per element | Compact storage |
What comes next
The string dtype addresses each row of that table. It holds only text and missing values. It uses a single missing-value marker, pd.NA. Its .str methods return proper nullable results. The next chapter introduces it. Later chapters cover its two storage backends and how pandas 3 changes the default.
Exercise
A Series s = pd.Series(["north", None, "south"], dtype=object) is filtered with s[s.str.contains("o")], and pandas raises a ValueError. Why does this happen, and what is the fix?
Show answer
On an object column, s.str.contains("o") returns an object Series [True, NaN, True], because the missing entry produces NaN instead of True or False. A mask that contains NaN is not a valid boolean indexer, so indexing raises ValueError. Pass na=False, as in s[s.str.contains("o", na=False)], so missing entries become False. Converting the column to the string dtype also fixes it, because the result then is a nullable boolean.
Exercise
A column has dtype object. Name two ways its contents could differ from "all text" even though the dtype looks the same, and one way to check.
Show answer
It could contain mixed types such as strings together with integers or floats, or it could contain non-text objects such as lists or dicts. Missing values may also appear as None, NaN, or pd.NA. To check, call pd.api.types.infer_dtype(s), which returns string for pure text and mixed or mixed-integer otherwise, or use s.map(type).value_counts() to count the Python types present.