Sub topic 1
Why Text in `object` Columns Is a Problem
Prerequisites
Assume you know basic Python strings, pandas Series and DataFrame objects, and the meaning of a pandas dtype.
Why text in `object` columns is a problem
An object column stores references to arbitrary Python objects. It often contains strings, but pandas does not know that every value is text. The same column can contain strings, None, numbers, lists, or custom objects.
This flexibility makes text operations less predictable. Missing values can appear as None or NaN, and operations may return different Python types. It also prevents pandas from applying text-specific storage and processing efficiently.
import pandas as pd
values = pd.Series(["apple", "banana", None])
print(values.dtype)
values.loc[1] = 42
print(values.tolist())The initial dtype is usually object. After the assignment, the column still accepts the integer because object does not enforce a text-only contract.
Meet the string dtype
Pandas provides the dedicated string dtype, implemented by StringDtype. It declares that the column contains text or missing values. Use dtype="string" when creating a Series, or use astype("string") to convert an existing one.
import pandas as pd
s = pd.Series(["apple", "banana", None], dtype="string")
print(s)
print(s.dtype)
print(s.isna().tolist())The dtype is string, and the missing entry is represented internally as pd.NA. This gives pandas a consistent representation for text columns and makes later .str operations easier to reason about.
Missing values in text columns
Missing-value behavior depends on the dtype. In an object column, missing values commonly appear as None or floating-point NaN. In a string column, pandas uses pd.NA.
import pandas as pd
object_s = pd.Series(["A", None])
string_s = object_s.astype("string")
print(object_s.dtype, object_s.iloc[1] is None)
print(string_s.dtype, string_s.iloc[1] is pd.NA)Both values are missing according to isna(), but pd.NA supports pandas’ nullable semantics. Text methods preserve missing values instead of silently turning them into ordinary strings.
Exercise
Why is dtype="string" safer than relying on an object dtype for a text column?
Show answer
It declares that values are text or missing, uses consistent pd.NA missing values, and makes text operations more predictable.