Sub topic 4
Cleaning strings before you convert
This chapter assumes you can build a DataFrame, select columns, and load a CSV with pandas. It also assumes you know that text columns have the object or string dtype.
Why clean first
astype(float) and pd.to_numeric only parse text that already looks like a number. A value such as "$1,200" has a currency symbol and a thousands separator, so the parser rejects it. astype raises a ValueError. pd.to_numeric with errors="coerce" silently turns the value into NaN, which destroys good data.
The fix is to remove the formatting from the text first, then convert.
The .str accessor
The .str accessor applies string methods to every element of a text column. Missing values pass through as NaN and do not raise errors.
import pandas as pd
df = pd.DataFrame({"price": ["$1,200", " $85 ", "n/a"]})
cleaned = df["price"].str.strip().str.replace(r"[$,]", "", regex=True)
print(cleaned)The chain does two things:
str.strip()removes leading and trailing spaces, which often arrive with exported data.str.replace(r"[$,]", "", regex=True)deletes every$and,. Inside square brackets,$is a literal character.
Pass regex=True explicitly. In current pandas versions str.replace treats the pattern as plain text by default, so a regular expression would match nothing without it.
Common cleaning methods
| Problem | Method |
|---|---|
| Extra spaces | `.str.strip()` |
| Mixed case such as `"Yes"` and `"YES"` | `.str.lower()` |
| Symbols such as `$`, `%`, `,` | `.str.replace(pattern, "", regex=True)` |
| Number buried in text such as `"12 kg"` | `.str.extract(r"(\d+\.?\d*)")` |
Handling several formats at once
Real columns often mix formats. This example handles accounting-style negatives, where (85) means -85.
import pandas as pd
s = pd.Series(["$1,200", "($85)", " 42 ", None])
step = (
s.str.strip()
.str.replace(r"^\((.*)\)$", r"-\1", regex=True)
.str.replace(r"[$,]", "", regex=True)
)
print(step.tolist())
print(pd.to_numeric(step).tolist())The first replacement captures the text inside the parentheses with (.*) and rewrites it as - followed by that text (\1). The second replacement then removes the currency symbols. Order matters here. If you removed $ first, the pattern would still work, but you should always check the intermediate result with print before converting.
The None stays missing at every step. pd.to_numeric then returns a float column, because NaN is a float.
Common errors
AttributeError: Can only use .str accessor with string values. The column is already numeric, or it holds mixed types. Checkdf.dtypes. If a column has some real numbers and some strings, call.astype("string")first.- Nothing changed after
replace. You probably forgotregex=True, or you did not assign the result back. String methods return a new Series and leave the original alone. - A pattern removed too much.
r"[^\d.]"deletes everything except digits and dots. That also strips the minus sign from negative numbers, so use it only on columns that cannot be negative. - Locale formats.
"1.200,50"uses a dot for thousands and a comma for decimals. Removing commas gives the wrong number. Remove the dots first, then change the comma to a dot.
Exercise
A column holds the strings "12%", " 7.5% ", and "n/a". Write the cleaning step that leaves "12", "7.5", and "n/a" as text, ready for pd.to_numeric.
Show answer
Use s.str.strip().str.replace("%", "", regex=False). Strip removes the surrounding spaces, and replace deletes the percent sign. Because "%" has no special meaning in a regular expression, regex=False works too. The "n/a" value is unchanged and is still text, so pd.to_numeric(..., errors="coerce") would turn it into NaN.
Exercise
Why does df["qty"].str.strip() raise an AttributeError when qty already has the int64 dtype?
Show answer
The .str accessor works only on text values. An int64 column has no strings to strip, so there is nothing to clean and the column can be used as it is.