Sub topic 4
Cleaning strings before you convert
This chapter covers the string-cleaning step that comes before astype, pd.to_numeric and pd.to_datetime. It assumes you can index a DataFrame and Series, read a CSV with pd.read_csv, and write basic Python and simple regular expressions. It also assumes you have inspected your dtypes and know why messy columns end up as object.
Why clean first
A converter can only parse text that looks like the target type. "$1,200" is a price to a human but not a number to pandas. If you call pd.to_numeric(..., errors="coerce") directly, the value silently becomes NaN and you lose real data. If you leave the default errors="raise", the call stops with a ValueError.
Cleaning moves the text toward a canonical form, such as "1200" or "2024-01-05", so the converter succeeds on as many rows as possible. The values that still fail after cleaning are the ones that deserve a closer look (see the chapter on finding values that failed to convert).
The .str accessor
The .str accessor applies string methods to every element of a column. It works on object and string dtypes, and it returns a Series, so calls chain naturally.
import pandas as pd
prices = pd.Series([" $1,200 ", "$85", "n/a", None, "(40)"])
clean = (
prices.str.strip()
.str.replace(r"^\((.*)\)$", r"-\1", regex=True)
.str.replace(r"[$,]", "", regex=True)
)
print(clean.tolist())
print(pd.to_numeric(clean, errors="coerce").tolist())The steps are:
strip()removes leading and trailing whitespace. Python's strip also removes non-breaking spaces (\xa0), which often arrive from web pages and Excel exports.- The first
replacerewrites accounting negatives:"(40)"becomes"-40". The pattern captures what is inside the parentheses and writes it back with a minus sign. - The second
replacedeletes the dollar sign and the thousands separator. Nonestays missing all the way through, because.strmethods pass missing values along."n/a"is not touched by cleaning.errors="coerce"turns it intoNaNat the conversion step.
Regex or literal text
Since pandas 2.0, str.replace treats the pattern as literal text by default (regex=False). Older versions defaulted differently. Always pass regex= explicitly so the code means the same thing on every version, and so a reader can tell what you intended.
s = pd.Series(["1.5", "2.5"])
print(s.str.replace(".", "", regex=False).tolist())
print(s.str.replace(".", "", regex=True).tolist())The first call removes the dot and gives ['15', '25']. In the second call the dot is a regex wildcard that matches every character, so both values become empty strings. This is a common source of columns that mysteriously turn empty.
Common cleaning tasks
| Problem | Example input | Approach |
|---|---|---|
| Padding | `" 42 "` | `str.strip()` |
| Currency and separators | `"$1,200"` | `str.replace(r"[$,]", "", regex=True)` |
| Accounting negatives | `"(40)"` | Rewrite with a captured group |
| Percent signs | `"12%"` | Remove `%`, then divide by 100 after conversion |
| Units attached to numbers | `"12 kg"` | `str.extract` with a capture group |
| Inconsistent case | `"Yes"`, `"YES"` | `str.lower()` |
| Placeholder text | `"n/a"`, `"-"`, `""` | Map to missing, or let `errors="coerce"` handle it |
| Decimal comma | `"1.234,56"` | Remove `.`, then replace `,` with `.` |
Decimal commas
Locale formats need two steps in the right order. Remove the thousands separator first, then change the decimal separator. If you swap the order, you destroy the decimal point.
eu = pd.Series(["1.234,56", "12,5", "980"])
text = eu.str.replace(".", "", regex=False).str.replace(",", ".", regex=False)
print(pd.to_numeric(text).tolist())The result is [1234.56, 12.5, 980.0].
If the whole file uses one locale, pd.read_csv can do this for you with decimal="," and thousands=".". Cleaning by hand is for columns where formats are mixed or the data did not come from a CSV.
Extracting a number from text
When the number is embedded in other text, extracting it is often safer than deleting everything around it. str.extract returns the first match of each capture group. With expand=False and a single group, you get a Series instead of a DataFrame.
weights = pd.Series(["12 kg", "7.5kg", "n/a", "30 KG"])
kg = weights.str.extract(r"(?i)(\d+(?:\.\d+)?)\s*kg", expand=False)
print(pd.to_numeric(kg).tolist())The result is [12.0, 7.5, nan, 30.0]. Rows with no match produce NaN, which flows into the numeric column as a missing value. The inline (?i) flag makes the match case-insensitive. The (?:...) group is non-capturing, so the extract still returns a single column.
Normalizing missing markers
Real files use many words for "no value": "n/a", "NA", "null", "-", and empty strings. Pandas only recognizes some of them automatically when reading a CSV, and none of them after the data is loaded. You can map them to missing explicitly before conversion.
MISSING = {"", "n/a", "na", "null", "-"}
def clean_number(s: pd.Series) -> pd.Series:
text = s.astype("string").str.strip()
text = text.mask(text.str.lower().isin(MISSING))
text = text.str.replace(r"^\((.*)\)$", r"-\1", regex=True)
text = text.str.replace(r"[$€£,%\s]", "", regex=True)
return pd.to_numeric(text, errors="coerce")
raw = pd.Series([" $1,200 ", "N/A", "(40)", "12%", "", None])
print(clean_number(raw).tolist())The values 1200, -40 and 12 convert, and the rest become missing. The exact result dtype (float64 or the nullable Float64) depends on your pandas version, so check .dtype if later code depends on it. The % is only removed. If 12% should mean 0.12, divide by 100 after conversion, and only for rows that had a percent sign.
Putting the logic in a function gives you one place to fix the rules, and you can reuse it on every column that shares the format.
Gotchas with .str
Non-string values become NaN
In an object column that mixes strings and numbers, .str methods return NaN for the elements that are not strings. This is a quiet data-loss bug.
mixed = pd.Series(["1,5", 3, None], dtype=object)
print(mixed.str.replace(",", ".", regex=False).tolist())
fixed = mixed.astype("string").str.replace(",", ".", regex=False)
print(fixed.tolist())The first line prints ['1.5', nan, nan], so the integer 3 was lost. After astype("string"), every element is text (3 becomes "3") and only the true missing value stays missing: ['1.5', '3', <NA>]. Converting to string first is a cheap safeguard whenever a column might hold mixed Python types.
The accessor fails on numeric columns
If a column is already int64 or float64, .str raises AttributeError: Can only use .str accessor with string values!. That is usually good news, because the column needs no string cleaning. If you see it on a column you thought was text, inspect df.dtypes and df[col].map(type).value_counts() to find out what is really inside.
Cleaning does not change the dtype
After str.replace, the column is still text. "1200" is not yet 1200. You must still call pd.to_numeric or astype to finish. Forgetting this step leaves a column that looks right when printed but still sorts alphabetically, so "85" ends up after "1200".
Assign the result back
String methods return a new Series. They do not modify the column in place. Write df["price"] = df["price"].str.replace(...), or build a cleaned Series and convert it in the same expression.
Dates need cleaning too
Date text has its own noise: trailing time zone words, ordinal suffixes like "5th", or mixed separators such as "2024/01/05" and "2024-01-05". Normalize separators and strip junk first, then pass an explicit format= to pd.to_datetime. Fewer formats in the input means fewer surprises in the parse.
dates = pd.Series(["2024/01/05", " 2024-02-10", "2024.03.15 "])
iso = dates.str.strip().str.replace(r"[/.]", "-", regex=True)
print(pd.to_datetime(iso, format="%Y-%m-%d").tolist())Checking your work
After cleaning and converting, compare counts. The number of missing values should rise only by the amount you expect.
before = raw.isna().sum()
after = clean_number(raw).isna().sum()
print(before, after)Here before is 1 (the None) and after is 3 (the None, "N/A" and the empty string). A larger jump would mean your rules removed data you meant to keep.
Exercise
A column amount has the values ["€1.234,50", " 99,90 ", "n/a"]. Write code that produces a float column with 1234.5, 99.9 and a missing value. Why must the thousands separator be removed before the decimal comma is replaced?
Show answer
Use s = df["amount"].astype("string").str.strip().str.replace("€", "", regex=False).str.replace(".", "", regex=False).str.replace(",", ".", regex=False) and then df["amount"] = pd.to_numeric(s, errors="coerce"). The "n/a" row cannot be parsed, so errors="coerce" makes it missing. The dot must be removed first because the next step turns the decimal comma into a dot. If you replaced the comma first, the string would contain two dots, such as "1.234.50", and you could no longer tell which dot was the separator and which was the decimal point. pd.to_numeric would also fail on it.
Exercise
You run s.str.replace(".", "", regex=True) on ["3.5", "4.25"] and get two empty strings. What went wrong, and what is the fix?
Show answer
With regex=True the pattern "." matches any single character, so every character is deleted. Use regex=False to treat the dot as literal text, or escape it as r"\." when using regex.