Sub topic 12
Pitfalls and a checklist
This chapter collects the mistakes that come up most often with text columns in pandas, explains the mechanism behind each, and ends with a checklist. It assumes you have read the earlier chapters. You should be comfortable with the string dtype, the .str accessor, pd.NA, and basic regular expressions.
Where the pitfalls come from
Most text bugs come from one of four causes:
- A column holds more than text, because
objectaccepts any Python value. - Missing values behave differently in
objectandstringcolumns. - A
.strmethod treats its pattern as a regular expression when you meant a literal. - A result has a different shape or dtype than you assumed, for example a column of lists instead of two columns.
The diagram shows where each cause enters a typical cleaning pipeline.
Pitfall 1: Comparisons treat missing values differently
In an object column, comparing with == gives a plain True or False for a missing entry. In a string column, the comparison returns <NA>, because the answer is unknown. The same entry gives opposite results for != in the two dtypes.
import pandas as pd
obj = pd.Series(["apple", None, "kiwi"], dtype=object)
txt = obj.astype("string")
print((obj == "apple").tolist())
print((obj != "apple").tolist())
print((txt == "apple").tolist())
print((txt != "apple").tolist())The first two lines print [True, False, False] and [False, True, True]. The last two keep <NA> in the middle position. In the object column, the missing entry counts as "not apple". In the string column, it stays unknown.
Neither behavior is wrong, but code moved from one dtype to the other can change which rows it selects. When you filter, decide what a missing value should do and write that decision down, for example with fillna("") or an explicit isna() test.
Never test for missing values with == None or == pd.NA. Both comparisons are unreliable. Use isna() and notna().
Pitfall 2: Boolean masks that contain missing values
On an object column, .str.contains returns an object Series with NaN wherever the input was missing. Using that Series as a mask fails.
import pandas as pd
obj = pd.Series(["apple", None, "kiwi"], dtype=object)
try:
print(obj[obj.str.contains("a")])
except ValueError as err:
print("ValueError:", err)
print(obj[obj.str.contains("a", na=False)])The first attempt raises a ValueError about masking with a non-boolean array. The second works because na=False turns each missing entry into False before the mask is built.
Use na=False when you want "keep only rows that clearly match". Use na=True when you want "drop only rows that clearly do not match". Pass it every time you filter, on either dtype. The code then works the same in both.
Pitfall 3: Accidental regular expressions
Several .str methods take a pattern. contains interprets it as a regular expression by default. A pattern with special characters such as (, [, +, *, . or ? then either fails or matches more than you intended.
import re
import pandas as pd
s = pd.Series(["f(x)", "g[1]", "plain"], dtype="string")
try:
s.str.contains("(")
except Exception as err:
print("error:", type(err).__name__)
print(s.str.contains("(", regex=False).tolist())
print(s.str.contains(re.escape("[1]")).tolist())The unescaped ( is an incomplete group, so the first call raises an error. The literal search prints [True, False, False]. The escaped pattern prints [False, True, False].
The worse case is a pattern that is valid but wrong. The pattern "1.5" matches "1x5" because . matches any character. No error warns you.
Rules that avoid this class of bug:
- Pass
regex=Falsewhenever you are searching for a fixed piece of text. - Use
re.escapewhen you build a regex from user input or from data. - Remember that
str.replacehas defaulted toregex=Falsesince pandas 2.0. Older code may have relied on the earlier default, so check which version a script was written for. - State
regex=explicitly even when it matches the default. A reader then does not need to know the default.
Pitfall 4: Splits and extracts that change shape
str.split without expand=True returns a Series of Python lists, stored in an object column. You cannot use .str string methods on those lists the way you would on text, and you lose all the benefits of the string dtype.
With expand=True you get a DataFrame, but the number of columns depends on the longest split. Rows with fewer pieces get missing values in the extra columns. Setting n limits the split and fixes the number of columns.
import pandas as pd
s = pd.Series(["a b c", "d e", "f"], dtype="string")
print(s.str.split(" ", expand=True))
print(s.str.split(" ", n=1, expand=True))The first call produces three columns, because the longest row has three parts. The second always produces two columns, and the second column holds the rest of the text.
str.extract has its own rules:
- The pattern must contain at least one capture group. Without one, pandas raises a
ValueError. - With one group and
expand=False, you get a Series. Withexpand=Trueyou get a DataFrame, even for one group. - Rows that do not match get
<NA>, with no error. A pattern that matches nothing returns a column that is entirely missing.
import pandas as pd
s = pd.Series(["id-001", "id-042", "unknown"], dtype="string")
try:
s.str.extract(r"\d+")
except ValueError as err:
print("ValueError:", err)
ids = s.str.extract(r"id-(\d+)", expand=False)
print(ids.isna().sum())After any extract, count the missing results, as the last line does. A high count usually means the pattern is wrong or the data has a variant you did not expect.
Pitfall 5: Result dtypes differ between object and string
The same method can return a different dtype depending on the input. For str.len, an object column with a missing value returns floating point numbers, because only floats can hold NaN. A string column returns the nullable integer type Int64.
import pandas as pd
obj = pd.Series(["apple", None, "kiwi"], dtype=object)
txt = obj.astype("string")
print(obj.str.len().dtype)
print(txt.str.len().dtype)The first line prints float64 and the second prints Int64. Lengths of 5.0 and 4.0 look odd and can break code that uses the lengths as integer positions or as keys. Check the dtype of a result before you pass it to code that expects integers or booleans.
Pitfall 6: Writing non-strings into a string column
A string column accepts only text and missing values. Assigning a number raises an error. An object column accepts anything, so the same assignment succeeds there and leaves a mixed column behind.
import pandas as pd
t = pd.Series(["a", "b"], dtype="string")
try:
t[0] = 5
except (TypeError, ValueError) as err:
print(type(err).__name__)
t[0] = str(5)
print(t.tolist())The error is the intended behavior, because it stops a mixed column from forming. Convert the value with str() before you assign it.
A related trap is astype(str) on an object column in pandas 2.x. It turns None into the text "None" and NaN into the text "nan". Those words are then real strings that no longer count as missing. Use astype("string") instead, which keeps missing values as <NA>. In pandas 3, the behavior of astype(str) changes with the new default str dtype, so test it on your version.
Pitfall 7: Hidden differences in the text itself
Some bugs are in the data. The values "Oslo", "Oslo " and "oslo" are three different strings. They show up as three categories in a groupby, as three keys in a join, and as non-matching values in a comparison.
Before you group, join, or compare on a text column, normalize it:
- Remove outer whitespace with
str.strip(). - Choose a case with
str.lower()orstr.casefold(). - Look for empty strings. An empty string
""is not missing, soisna()does not report it. Convert it withreplace("", pd.NA)if you want it treated as missing.
Pitfall 8: Preparing for pandas 3
In pandas 3, a column built from Python strings gets the default str dtype instead of object. Code that checked dtype == object to find text columns stops finding them. Use select_dtypes(include=["object", "string"]), or add the "str" alias for pandas 3, so the selection works on both.
The default str dtype also uses NaN as its missing marker, not pd.NA. Code that tests specifically for pd.NA, or that relies on <NA> propagating through comparisons, needs a review. Check the pandas 3 release notes for the exact rules for your version.
Summary table
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError` when filtering with `.str.contains` | Mask contains missing values | Pass `na=False` |
| `re.error`, or too many matches | Literal text treated as regex | Use `regex=False` or `re.escape` |
| Column of lists after split | `expand=False` | Use `expand=True`, set `n` |
| Extract returns all `<NA>` | Pattern matches nothing | Test the pattern, count missing |
| Lengths show as floats | `object` column with `NaN` | Convert to `string` |
| Words `"None"` or `"nan"` in the data | `astype(str)` on `object` | Use `astype("string")` |
| Same value appears as several groups | Whitespace or case differences | Strip and normalize |
| `TypeError` on assignment | Non-string value | Convert with `str()` first |
A checklist for text columns
Run through this list when you start working with a new text column.
- Check
df.dtypesanddf.info(). If a column isobject, decide whether it is really text. - Convert text columns with
convert_dtypes()orastype("string")early, so the rest of the code sees one consistent type. - Count missing values with
isna().sum()and decide how each one should behave in filters and joins. - Pass
na=to everycontains,startswith, andendswithcall that builds a mask. - Pass
regex=explicitly. Useregex=Falsefor fixed text andre.escapefor patterns built from data. - Strip whitespace and fix the case before grouping, joining, or comparing.
- After
splitandextract, check the number of columns and the count of missing results. - Check the dtype of each result before using it as an index, a mask, or an integer.
- If a column has few distinct values, compare memory with
astype("category"). - Test the code against the dtype that pandas 3 will use by default, so the upgrade does not surprise you.
Exercise
A Series s = pd.Series(["a.b", "axb", None], dtype="string") is searched with s.str.contains("a.b"). What does it return, and how do you make it match only the literal text a.b while giving False for the missing entry?
Show answer
The default pattern is a regular expression, where . matches any character, so both "a.b" and "axb" give True. The missing entry gives <NA>. Use s.str.contains("a.b", regex=False, na=False). The result is [True, False, False].
Exercise
You run df["code"] = df["raw"].str.extract(r"\d+") and get a ValueError. Explain why, and write a corrected line that extracts the digits after the text id-. Name one check to run afterward.
Show answer
str.extract requires at least one capture group, and \d+ has none. The corrected line is df["code"] = df["raw"].str.extract(r"id-(\d+)", expand=False). Afterward, run df["code"].isna().sum() to count the rows that did not match.