Sub topic 3
Missing values in text columns
This chapter covers how pandas represents a missing string, how that representation changes between object and string columns, and what happens to missing entries when you use .str methods, comparisons, and filters. It assumes you can create Series and DataFrames, know what a dtype is, and have met the string dtype in the previous chapters. The examples were written for pandas 2.x. The section on pandas 3 near the end covers what changes there.
Three markers for "nothing here"
A text column can show a missing entry in three ways:
None, the Python null object.numpy.nan, a floating-point "not a number" value.pd.NA, the scalar pandas introduced for missing values in nullable dtypes.
An object column can hold all three at once. pd.isna recognizes each of them, so detection works. The trouble starts when you do something with the values.
import numpy as np
import pandas as pd
s = pd.Series(["a", None, np.nan, pd.NA])
print(s.dtype)
print(s.isna().tolist())
print(s.map(repr).tolist())The dtype is object, isna reports [False, True, True, True], and the repr list is ['a', 'None', 'nan', '<NA>']. Three different markers live in one column, and they behave differently in comparisons and in conversions.
What the string dtype changes
A string column has exactly one missing marker, pd.NA. Whatever you put in (None, np.nan, or pd.NA) is stored as pd.NA.
import numpy as np
import pandas as pd
s = pd.Series(["a", None, np.nan, pd.NA], dtype="string")
print(s)
print(s.isna().tolist())
s.iloc[0] = None
print(s.isna().tolist())All four entries print as a or <NA>, and after the assignment the first entry is missing as well. The column cannot hold a stray nan float or a None that later behaves differently from its neighbors.
pd.NA also has one rule that explains most of what follows: a result that depends on an unknown value is unknown. Comparing pd.NA to anything gives pd.NA, not False.
Propagation through .str methods
On both dtypes, a .str method does not fail on a missing entry. It returns a missing entry at that position. The difference is the type of the rest of the result.
import pandas as pd
raw = pd.Series(["alpha", "sky", None])
typed = raw.astype("string")
print(raw.str.len())
print(typed.str.len())On the object column the result is float64, with 5.0, 3.0, and NaN. The integers became floats only because NaN is a float. On the string column the result is Int64, with 5, 3, and <NA>, so the lengths stay integers.
Predicates follow the same pattern. str.contains, str.startswith, and str.isdigit return an object column holding True, False, and NaN on an object input. On a string input they return the nullable boolean dtype with <NA>.
| Operation | `object` column | `string` column |
|---|---|---|
| Missing markers | `None`, `NaN`, `pd.NA` mixed | `pd.NA` only |
| `str.len()` | `float64` with `NaN` | `Int64` with `<NA>` |
| `str.contains("a")` | `object` with `True`, `False`, `NaN` | `boolean` with `<NA>` |
| `s == "x"` on a missing entry | `False` | `<NA>` |
| Filtering with the `contains` result | `ValueError` | Missing entries treated as `False` |
| `astype(str)` | Missing becomes the text `"None"` or `"nan"` | Not applicable, use `astype("string")` |
Filtering with masks
The filtering row of the table has the most practical effect. A boolean mask that contains missing entries is ambiguous: should a row with an unknown answer be kept?
import pandas as pd
raw = pd.Series(["alpha", "sky", None])
typed = raw.astype("string")
mask_obj = raw.str.contains("a")
try:
raw[mask_obj]
except ValueError as err:
print("object:", err)
mask_str = typed.str.contains("a")
print(mask_str.dtype)
print(typed[mask_str])The object version raises ValueError because the mask contains NaN. The string version works, because indexing with a nullable boolean mask treats <NA> as False. The result keeps only alpha.
Do not rely on that implicit rule. Say what you mean with the na argument that the predicate methods accept:
import pandas as pd
s = pd.Series(["alpha", "sky", None], dtype="string")
print(s[s.str.contains("a", na=False)])
print(s[s.str.contains("a", na=True)])The first line keeps rows that definitely match. The second keeps rows that match or are unknown. Both choices are legitimate, and writing the argument makes the choice visible to the next reader. The same code then works on an object column too.
Comparisons and truthiness
Equality on a string column propagates missingness instead of returning False.
import pandas as pd
obj = pd.Series(["x", None])
typed = pd.Series(["x", None], dtype="string")
print((obj == "x").tolist())
print((typed == "x").tolist())
try:
if typed[1] == "x":
print("match")
except TypeError as err:
print("TypeError:", err)The object column gives [True, False]. The string column gives [True, <NA>]. The if statement raises TypeError, because pd.NA refuses to become a plain True or False. This is deliberate. It stops you from silently treating "unknown" as "no".
When you do want a two-valued answer, convert explicitly:
import pandas as pd
typed = pd.Series(["x", None], dtype="string")
is_x = (typed == "x").fillna(False)
print(is_x.tolist())
print(typed.isin(["x"]).tolist())fillna(False) states the decision. isin is also a clean option, because it returns a plain boolean result and a missing entry counts as "not in the list".
Empty strings are not missing
An empty string "" is a real value. It is not detected by isna, it has length 0, and it compares equal to "".
import pandas as pd
s = pd.Series(["a", "", None, "b", "a"], dtype="string")
print(s.isna().sum())
print((s == "").sum())
print(s.str.len().tolist())The count of missing entries is 1, the count of empty strings is 1, and the lengths are [1, 0, <NA>, 1, 1]. If your data uses "" to mean "unknown", convert it once, early, so later steps handle only one kind of absence:
import pandas as pd
s = pd.Series(["a", "", None, "b", "a"], dtype="string")
cleaned = s.replace("", pd.NA)
print(cleaned.isna().sum())After this the count is 2. Whitespace-only entries need s.str.strip() first, because " " is neither empty nor missing.
Missing values on the way in
Many "missing text" problems start in the file reader. read_csv converts an empty field to missing, and it also converts several literal strings by default, including NA, NULL, and NaN. That is a problem when NA is a real value, such as the country code for Namibia.
from io import StringIO
import pandas as pd
data = "code,country\nNA,Namibia\nUS,United States\n,Unknown\n"
default = pd.read_csv(StringIO(data), dtype="string")
print(default["code"].isna().tolist())
strict = pd.read_csv(
StringIO(data),
dtype="string",
keep_default_na=False,
na_values=[""],
)
print(strict["code"].isna().tolist())The default reader reports [True, False, True], so the Namibia row lost its code. With keep_default_na=False and na_values=[""], only the empty field is missing and the result is [False, False, True]. Passing dtype="string" ensures the column is created as string without a detour through object.
Converting without losing missingness
Converting with astype(str) is the classic way to turn missing values into text by accident. Python's str is applied to each element, including the missing ones.
import numpy as np
import pandas as pd
s = pd.Series(["a", None, np.nan])
print(s.astype(str).tolist())
print(s.astype("string").isna().tolist())The first line prints ['a', 'None', 'nan']. Those are now ordinary strings that isna will not find, and they will show up as categories, group keys, and join keys. The second line prints [False, True, True], so the missing entries survived. Use astype("string") (with the quotes) for text columns. Reserve astype(str) for the rare case where you really want the literal text.
Counting, filling, and dropping
The standard tools work on string columns, but a few defaults hide missing data.
import pandas as pd
s = pd.Series(["a", None, "b", "a", None], dtype="string")
print(s.isna().sum())
print(s.value_counts())
print(s.value_counts(dropna=False))
print(s.fillna("unknown").tolist())
print(s.dropna().tolist())value_counts() leaves missing entries out unless you pass dropna=False. groupby behaves the same way: rows whose key is missing are dropped unless you pass dropna=False to groupby. Check these defaults before comparing counts against len(s).
Fill values must be strings in a string column. fillna("unknown") works, and fillna(0) does not make sense for text.
A useful habit is to measure the missing share before you clean anything:
import pandas as pd
df = pd.DataFrame(
{"city": ["Oslo", None, "Lima"], "note": [None, None, "ok"]},
dtype="string",
)
print(df.isna().mean())This prints the fraction missing per column, here about 0.33 for city and 0.67 for note.
A note on pandas 3
In pandas 3 the default text dtype is str, which is backed by the same ideas as string, but its missing marker is NaN rather than pd.NA. As a result, comparisons and .str predicates on a default str column return plain bool results, with False at missing positions, much as object columns do today. The explicit dtype="string" still uses pd.NA with the behavior described above. Code that depends on <NA> propagation, such as .fillna(False) after a comparison, usually keeps working, but any check that tests the identity of the marker should use isna instead. A later chapter covers the migration in detail.
Pitfalls checklist
- Test for missing entries with
isna(), never with== Noneor== np.nan. - Do not use a mask from a text predicate without deciding what
nameans. - Do not call
astype(str)on a column that may contain missing entries. - Do not use a missing-capable comparison inside a Python
iforand. Reduce it first withfillna,any(), orall(). - Decide whether
""and whitespace-only entries mean "missing" and convert them once. - Check the CSV defaults when a column contains legitimate values such as
NAorNULL.
Exercise
A string column s contains ["red", None, "blue"]. What do s.str.contains("e"), s[s.str.contains("e", na=False)], and (s == "red").tolist() produce?
Show answer
s.str.contains("e") gives a boolean Series [True, <NA>, True]. The filter keeps rows 0 and 2 (red and blue), because na=False makes the missing row a non-match. The comparison gives [True, <NA>, False], because comparing pd.NA to "red" is unknown rather than False.
Exercise
A CSV column status contains the literal values ok, NA, and an empty field. You want NA kept as text and only the empty field treated as missing, and you want the column read as string. Write the read_csv call, and explain why astype(str) would be the wrong tool for repairing a column that was already read with missing entries.
Show answer
Use pd.read_csv(path, dtype="string", keep_default_na=False, na_values=[""]). With keep_default_na=False, the built-in list that includes NA is turned off, and na_values=[""] adds back only the empty field. astype(str) would turn each missing entry into the text "None" or "nan", which isna no longer detects, so later counts, groups, and joins would treat them as real values.