Sub topic 3
Missing values in text columns
This chapter assumes you can create a Series, you know what a dtype is, and you have met None and NaN before. By the end you should be able to predict what .str methods return when a text column has gaps.
Three ways to be missing
An object column can hold any Python value, so a gap can take several forms:
None, the Python null object.np.nan, a floating-point "not a number" value.pd.NA, pandas' own missing-value marker, introduced for the nullable dtypes.
In an object column, None and np.nan can sit side by side. isna() treats both as missing, but the column stays a mix of types.
The string dtype uses one marker, pd.NA. Converting with astype("string") turns every None and NaN into pd.NA.
import numpy as np
import pandas as pd
raw = pd.Series(["apple", None, np.nan, "cherry"], dtype=object)
print(raw.tolist())
print(raw.isna().tolist())
clean = raw.astype("string")
print(clean.tolist())
print(clean.isna().tolist())The first list shows None and nan mixed in. The converted list shows <NA> in both places. isna() gives the same answer for both columns.
How results differ
The marker affects the dtype of the results. On an object column, .str methods that return numbers or booleans fall back to float64 or object, because a missing entry has to be stored as NaN or None. On a string column, the results use the nullable dtypes Int64 and boolean, which can hold pd.NA.
import pandas as pd
values = ["apple", "banana", None]
obj = pd.Series(values, dtype=object)
txt = pd.Series(values, dtype="string")
print(obj.str.len().dtype)
print(txt.str.len().dtype)
print(obj.str.contains("an").dtype)
print(txt.str.contains("an").dtype)The four lines print float64, Int64, object and boolean.
| Operation | On object column | On string column |
|---|---|---|
| `.str.len()` | `float64` with `NaN` | `Int64` with `<NA>` |
| `.str.contains(...)` | `object` holding `True`, `False` and a missing marker | `boolean` with `<NA>` |
| `.str.upper()` | missing entries stay missing | missing entries become `<NA>` |
| `.isna()` | `bool` | `bool` |
The length example shows why this matters. A column of integer lengths silently becomes floats on an object column, just because one entry is missing.
Filtering with missing values
A boolean mask with gaps is the most common source of errors. With an object column, contains returns an object Series that includes missing entries. Using it as a mask raises a ValueError about masking with non-boolean values containing NA. A boolean result can be used as a mask, and <NA> entries are treated as False. Relying on that is easy to forget, so state your intent with na=.
import pandas as pd
s = pd.Series(["apple", "banana", None], dtype="string")
print(s.str.contains("an").tolist())
print(s.str.contains("an", na=False).tolist())
print(s[s.str.contains("an", na=False)])The first list is [False, True, <NA>]. With na=False it becomes [False, True, False], so the gap is excluded from the filter. Use na=True if rows with missing text should be kept.
Comparisons follow the same rule. s == "apple" on a string column returns <NA> for the missing row, not False. If you need a plain True or False, call .fillna(False) on the result, or use isna() separately.
Filling and dropping
Fill missing text before applying methods that need a real string:
import pandas as pd
s = pd.Series(["apple", None, "cherry"], dtype="string")
print(s.fillna("unknown").str.title().tolist())
print(s.dropna().tolist())This prints ['Apple', 'Unknown', 'Cherry'] and then ['apple', 'cherry']. Choose deliberately: filling with an empty string "" makes a missing value look like real data, and isna() will no longer find it.
Common errors
- Mixing
NoneandNaNin an object column and expecting identical behavior everywhere. Convert tostringfirst. - Using a
.str.containsresult as a mask on an object column withoutna=. This raises aValueError. - Expecting
s == "x"to beFalsefor missing rows. Onstringit is<NA>. - Filling with
""and then being unable to count missing rows.
Exercise
A string column s contains ["red", None, "blue"]. You want the rows whose text contains "r", and you want the missing row excluded. Which expression do you write, and what does the list s.str.contains("r").tolist() look like without na=False?
Show answer
Use s[s.str.contains("r", na=False)]. Without na=False, the list is [True, <NA>, False]. With na=False, the missing row becomes False and is excluded. Only "red" matches, because "blue" has no "r".