Sub topic 1
Why text in object columns is a problem
Prerequisites
This chapter assumes you can:
- Use basic Python strings and read simple regular expressions.
- Create and index pandas Series and DataFrames.
- Explain what a dtype is in pandas and NumPy.
The default container for text
NumPy arrays need every element to have the same fixed-size type. Python strings have variable length, so pandas has traditionally stored them in an object column. An object column is an array of pointers to ordinary Python objects. It can hold strings, integers, None, lists, or anything else.
That flexibility is the problem. The dtype object says "some Python things", not "text". pandas and you must inspect the values to find out what is inside.
import pandas as pd
s = pd.Series(["apple", "banana", None, 42])
print(s.dtype)
print(s.map(type).tolist())The dtype is object, and the types are str, str, NoneType, and int. Nothing stops a stray number or None from entering a text column.
Problem 1: the dtype does not tell you what is inside
Two object columns can look identical and behave differently. One may hold only strings. Another may hold strings mixed with numbers. You cannot tell from df.dtypes.
The .str accessor, which applies string methods to every element, also depends on what it finds inside:
- If a column mixes strings with other objects,
.strmethods quietly returnNaNfor the non-strings. - If every value is a non-string, such as integers, the accessor raises an error.
import pandas as pd
mixed = pd.Series(["apple", "banana", None, 42])
print(mixed.str.upper().tolist())
numbers = pd.Series([1, 2, 3], dtype=object)
try:
numbers.str.upper()
except AttributeError as err:
print("AttributeError:", err)The first call returns ['APPLE', 'BANANA', nan, nan]. The integer 42 was not converted. It was replaced by NaN, and no warning was raised. The second call fails with Can only use .str accessor with string values!. The same code can therefore succeed or fail depending on the data.
Problem 2: missing values are inconsistent
Object columns represent a missing entry with None or with float("nan"), depending on how the data arrived. isna() treats both as missing, so you may not notice which one you have. The results of .str methods then follow float rules.
import pandas as pd
s = pd.Series(["a", "bb", None])
print(s.str.len())
print(s.str.contains("a").tolist())str.len() returns 1.0, 2.0, NaN with dtype float64, even though lengths are whole numbers. The only way to hold a missing entry in a numeric result is to switch to floats. str.contains returns an object result, [True, False, nan], which is neither a clean boolean column nor safe to filter with.
import pandas as pd
s = pd.Series(["a", "bb", None])
try:
print(s[s.str.contains("a")])
except ValueError as err:
print("ValueError:", err)Using the result as a filter raises a ValueError, because a boolean mask cannot contain NaN. Many people hit this error when they first filter text data with missing entries.
Problem 3: memory and speed
Every element is a separate Python object, and the array only stores pointers to them. This costs more memory than a compact layout, and each .str method loops over Python objects one at a time. Later chapters measure this cost and show the alternatives.
Common mistakes
| Mistake | Symptom |
|---|---|
| Assuming an object column holds only text | `.str` returns `NaN` for stray numbers, with no error |
| Checking `dtype == object` to find text columns | Also matches lists, dates stored as objects, and mixed data |
| Using `.str.contains(...)` directly as a filter | `ValueError` when the column has missing values |
| Expecting integer results from `.str.len()` | Result is `float64` when any value is missing |
The next chapter introduces the dedicated string dtype, which fixes these problems by guaranteeing that every non-missing element is text and by using one marker, pd.NA, for missing values.
Exercise
A Series is created with pd.Series(["x1", "y2", None, 7]). You call .str.len() on it. What are the values and the dtype of the result, and why?
Show answer
The result is [2.0, 2.0, NaN, NaN] with dtype float64. The integer 7 is not a string, so .str returns NaN for it, and None is also missing. Because NaN can only be stored in a float column, the lengths are converted to floats.
Exercise
Why does s[s.str.contains("a")] raise a ValueError on an object column that contains None, and what is the underlying cause?
Show answer
str.contains returns an object result that includes NaN for the missing entry. A boolean mask cannot contain NaN, so pandas raises the error. The cause is that an object column has no dedicated missing-value type that keeps boolean results boolean.