Sub topic 4
Cleaning and searching text with .str
This chapter covers the everyday text operations in pandas: cleaning, measuring and searching. It assumes you know basic Python string methods and can create a Series or DataFrame. It also assumes you have met the string dtype and the idea of pd.NA from the earlier chapters. Regular expressions and splitting into columns get their own chapters, so they appear here only where they affect the methods below.
What the .str accessor does
Series.str is an accessor. It gives a Series of text a set of vectorized string methods. Most of them mirror Python's str methods (upper, strip, startswith). Each method is applied to every element, and the results come back as a new Series with the same index.
import pandas as pd
s = pd.Series([" Alice ", "BOB", None, "carol smith"], dtype="string")
print(s.str.strip())
print(s.str.lower())Missing entries are skipped, not passed to the Python method. A plain None.strip() would raise AttributeError. With .str, the missing entry stays missing in the result.
Python strings are immutable, and so is this operation. Every .str call returns a new Series. Nothing changes in place, so you must assign the result back if you want to keep it.
The accessor is available only when the Series holds text. On an int64 column, .str raises AttributeError: Can only use .str accessor with string values!. On an object column that mixes text with other values, the accessor is allowed. Elements that are not strings come out as NaN, which is one reason object columns are unreliable for text.
import pandas as pd
mixed = pd.Series(["a", 1, "c"])
print(mixed.str.upper().tolist())The middle element is not text, so it becomes nan and no error is raised. A column that mixes types can lose data this way, and you may not notice.
What each method returns
The result dtype depends on what kind of answer a method produces. On a string column, the dtype is predictable.
| Kind of method | Examples | Result dtype on `string` | Missing input gives |
|---|---|---|---|
| Returns text | `upper`, `lower`, `strip`, `replace`, `slice` | `string` | `<NA>` |
| Returns a number | `len`, `count`, `find` | `Int64` | `<NA>` |
| Returns a yes/no answer | `contains`, `startswith`, `endswith`, `isdigit` | `boolean` | `<NA>` |
On an object column the same methods return object or float64 results with NaN for missing entries. A length column with one missing value turns into floats on an object column. On a string column it stays integer-valued.
import pandas as pd
values = ["alpha", None, "gamma"]
obj = pd.Series(values)
txt = pd.Series(values, dtype="string")
print(obj.str.len().dtype)
print(txt.str.len().dtype)
print(obj.str.contains("a").dtype)
print(txt.str.contains("a").dtype)This prints float64, Int64, object and boolean.
Cleaning text
Most cleaning is a chain of small steps. Each .str method returns a Series, so you can call the next .str method directly on the result.
import pandas as pd
raw = pd.Series(
[" Alice ", "BOB", None, "carol smith", "Dave\t"],
dtype="string",
)
clean = (
raw.str.strip()
.str.lower()
.str.replace(r"\s+", " ", regex=True)
)
print(clean)The result is alice, bob, <NA>, carol smith and dave, with dtype string. The steps do the following:
strip()removes leading and trailing whitespace. Tabs and newlines count as whitespace, so"Dave\t"is cleaned too.lower()makes casing consistent.replace(r"\s+", " ", regex=True)collapses runs of internal whitespace into one space.
strip also accepts a set of characters to remove, such as .str.strip("-_ "). Use lstrip or rstrip to trim one side only.
Other cleaning methods you will use often:
str.title()andstr.capitalize()change casing for display.str.casefold()is a strongerlower()meant for comparing text across languages. For example, it maps the Germanßtoss.str.normalize("NFKC")converts equivalent Unicode forms to one form. Use it when the same visible character can arrive in two encodings, such as an accented letter written as one character or as a letter plus a combining mark.str.zfill(5)pads numeric-looking text with leading zeros, so"42"becomes"00042".str.slice(0, 3)andstr[:3]take part of each string.
import pandas as pd
codes = pd.Series(["7", "42", None, "1234"], dtype="string")
print(codes.str.zfill(5))
print(codes.str[:2])The first call gives 00007, 00042, <NA> and 01234. The second gives 7, 42, <NA> and 12.
Measuring text
str.len() returns the number of characters in each element. It counts characters, not bytes, and it counts spaces. Run it before and after cleaning to see what a step changed.
import pandas as pd
raw = pd.Series([" Alice ", "BOB", None], dtype="string")
print(raw.str.len().tolist())
print(raw.str.strip().str.len().tolist())This prints [8, 3, <NA>] and then [5, 3, <NA>]. The Int64 result keeps <NA> in place and does not turn the integers into floats.
str.count(pattern) returns how many times a pattern occurs in each string. Its pattern is a regular expression, so a character such as . matches any character. Escape such characters or choose a pattern that has no special meaning.
Searching text
Searching methods return one boolean per row. The main ones are:
str.contains(pat)tests whether the pattern appears anywhere in the string.str.startswith(pat)andstr.endswith(pat)test the ends of the string.str.match(pat)tests whether a regular expression matches from the start of the string.str.isdigit(),str.isalpha()andstr.isnumeric()test the character types in the string.
Take care with matching mode. contains treats its pattern as a regular expression by default. startswith and endswith always treat theirs as literal text. The next chapter covers the difference in detail. For now, pass regex=False to contains whenever the search text should be taken literally, and avoid surprises with characters like ., ( and +.
import pandas as pd
msgs = pd.Series(
["Error: disk full", "warning: low memory", None, "error: timeout"],
dtype="string",
)
print(msgs.str.contains("error", case=False, regex=False))case=False makes the search ignore case, so both Error and error match. The result is True, False, <NA>, True, with dtype boolean.
Filtering with a mask
A boolean Series can select rows. The missing entry is the complication. A mask that contains <NA> cannot say whether the row should be kept.
In a boolean mask, pandas treats <NA> as False when you index. That behavior is convenient, but it hides the decision. Passing na=False states it explicitly, and it also works on object columns, where a mask containing NaN can raise a ValueError.
import pandas as pd
msgs = pd.Series(
["error: disk full", "warning: low memory", None, "error: timeout"],
dtype="string",
)
errors = msgs[msgs.str.startswith("error", na=False)]
print(errors)This prints rows 0 and 3. The na argument sets the result for missing entries. Use na=False when you want to keep only confirmed matches. Use na=True when you want missing values to stay in a filter, for example when removing rows that match a bad pattern.
import pandas as pd
msgs = pd.Series(
["error: disk full", "warning: low memory", None, "error: timeout"],
dtype="string",
)
not_errors = msgs[~msgs.str.startswith("error", na=True)]
print(not_errors)Here the <NA> row is treated as an error by the test, and ~ then drops it. The result is only the warning row. If the missing row should stay in the result, use na=False before the ~.
Counting matches
Because a boolean Series is stored as zeros and ones when summed, you can count matches directly. sum() ignores <NA> in a boolean Series.
import pandas as pd
msgs = pd.Series(
["error: disk full", "warning: low memory", None, "error: timeout"],
dtype="string",
)
print(msgs.str.startswith("error").sum())
print(msgs.str.startswith("error").mean())This prints 2 and 1.0. The mean is taken over the two non-missing results of... correction: the mean is taken over the three non-missing entries, so it is 2/3, about 0.667. Check which one you need before you report a share, because the denominator excludes missing rows.
Replacing text
str.replace(pat, repl) substitutes text. In current pandas, set the matching mode explicitly with regex=True or regex=False, so the code reads the same under every version.
import pandas as pd
prices = pd.Series(["$1.50", "$12", None], dtype="string")
print(prices.str.replace("$", "", regex=False))With regex=False, the $ is a literal dollar sign. As a regular expression, $ means "end of string", and the call would not remove the symbol. The result is 1.50, 12 and <NA>.
To turn the cleaned text into numbers, convert with pd.to_numeric on the result.
import pandas as pd
prices = pd.Series(["$1.50", "$12", None], dtype="string")
numbers = pd.to_numeric(prices.str.replace("$", "", regex=False))
print(numbers)Common mistakes
- Forgetting to assign.
df["name"].str.strip()computes a cleaned Series and discards it. Writedf["name"] = df["name"].str.strip(). - Assuming
containsis literal. A search for"a.b"also matches"axb"unless you passregex=False. - Filtering without
na. On an object column, a mask withNaNcan fail. On astringcolumn, the choice is hidden. Setnaexplicitly. - Using
.stron non-text columns. Convert first withastype("string"). - Trusting an object column. Mixed values turn silently into
NaNunder.str.
Exercise
A column tag has dtype string and contains ["Py-3.12", "py-3.9", None, "Rust-1.80"]. Write one expression that returns only the rows whose value starts with "py" in any casing, treating missing values as non-matches. Why is str.startswith a poor choice here, and what do you use instead?
Show answer
str.startswith has no case argument, so it cannot ignore casing. Lowercase first and then test: df[df["tag"].str.lower().str.startswith("py", na=False)]. Alternatively, use df[df["tag"].str.contains("^py", case=False, na=False)], which is a regex match anchored at the start. Both return the first two rows. The <NA> row is excluded because of na=False.