Sub topic 12
Pitfalls and a checklist
This chapter assumes you know the earlier material: the string dtype, how pd.NA behaves, the .str accessor, literal versus regex matching, and astype/convert_dtypes. Here the pieces become a working routine. The chapter covers the mistakes that cause most text-column bugs, then a checklist to run before you trust a text column.
Common pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
| Mixed types in an `object` column | `.str` methods return missing values for non-strings | Convert to `string`, or clean the column first |
| Using a mask that contains missing values | `ValueError` when filtering | Pass `na=False`, or use the `string` dtype |
| Relying on the default for `regex` | `.` or `(` matches more or less than you meant | Always pass `regex=True` or `regex=False` |
| `astype(str)` on missing data (pandas 2) | `None` and `nan` become the text `"None"` and `"nan"` | Use `astype("string")` |
| `category` on mostly unique text | Memory goes up, not down | Keep `string` |
| `.str` on a non-text column | `AttributeError` | Convert the column first |
Mixed values hide inside object columns
An object column accepts anything. A stray number is not an error, but .str methods quietly turn it into a missing value.
import pandas as pd
raw = pd.Series(["Ann", 42, None, "bob"])
print(raw.dtype)
print(raw.str.upper())
clean = raw.astype("string")
print(clean.tolist())The number 42 and the None both come back from .str.upper() as missing, so you lose data without any warning. After astype("string") the 42 becomes the text "42" and the None becomes <NA>. That conversion may be what you want, but make it a deliberate choice. Check with raw.map(type).value_counts() before you convert.
Masks with missing values
On an object column, str.contains returns NaN for missing entries. Using that result as a filter raises an error. On a string column it returns <NA>, which is easier to handle. In both cases na=False states what a missing value should mean for your filter.
import pandas as pd
s = pd.Series(["a.b", None, "axb"], dtype="string")
print(s.str.contains(".", regex=False).tolist())
print(s.str.contains(".", regex=True, na=False).tolist())The first line prints [True, <NA>, False]. Only the literal dot in "a.b" matches, and the missing entry stays missing. The second line prints [True, False, True]. The regex . matches any character, and na=False turns the missing entry into False.
Regex defaults differ between methods
str.contains treats its pattern as a regex by default. str.replace treats it as literal text by default in pandas 2. Defaults like this have changed between versions, and a pattern such as "." or "(" behaves very differently in each mode. Passing regex= every time removes the doubt and makes the code safe to move between versions.
Splitting can produce ragged results
str.split(expand=True) creates as many columns as the longest result. A row with fewer pieces gets <NA> in the extra columns. Without expand=True you get a column of lists, and .str methods on that column behave differently again. Set n= so you know how many columns to expect, and check the new columns for <NA> after the split.
Category is not always smaller
The category dtype stores each distinct value once, plus an integer code for every row. That pays off when values repeat a lot. If most values are unique, you store the values and the codes, and memory rises. Compare memory_usage(deep=True) for both dtypes before you switch.
Choosing a representation
Checklist
- Inspect
df.dtypesand look forobjectcolumns that should hold text. - Check for mixed types with
s.map(type).value_counts(). - Convert with
astype("string")orconvert_dtypes(). Avoidastype(str)for columns with missing values. - Count missing values with
s.isna().sum()before and after each cleaning step. - Pass
regex=explicitly andna=for every filter built onstr.contains. - Check the output of
splitandextractfor<NA>rows. - For large columns, compare
memory_usage(deep=True)acrossstring(both backends) andcategory. - Check whether your code assumes
object. pandas 3 makesstrthe default text dtype, so test your code against it.
Exercise
A column s = pd.Series(["x1", None, "y2"], dtype="string") is used as df[s.str.contains("1")]-style filtering. You want rows containing the literal text 1, and you want missing rows excluded. Which call would you write, and why is each argument there?
Show answer
Use s.str.contains("1", regex=False, na=False). regex=False makes the match literal and independent of version defaults. na=False turns the <NA> for the missing row into False, so that row is dropped from the filter.
Exercise
Why can pd.Series(["a", 5, None]).str.upper() lose information, and what is one way to make the conversion explicit?
Show answer
On an object column, .str methods return a missing value for entries that are not strings, so the 5 is silently lost. Convert first with astype("string"), which turns 5 into the text "5" and None into <NA>. Alternatively, check the types with map(type).value_counts() and fix the bad entries before converting.