Sub topic 7
Finding the values that failed to convert
This chapter assumes you can build a DataFrame, select columns and rows with boolean masks, and have already used pd.to_numeric and pd.to_datetime with errors="coerce". The goal is to make sure no value disappears without you noticing.
Why failures go unnoticed
errors="coerce" makes a conversion finish instead of stopping at the first bad value. Every value that cannot be parsed becomes NaN (or NaT for dates). The result has the right dtype and no exception was raised, so the column looks fine.
The cost is that a parse failure and a value that was already missing now look identical. A column with 3% NaN after conversion could mean 3% were missing in the source, or 3% were typos you could have fixed. You can only tell by comparing the result with the input.
The core pattern: compare before and after
A value failed to convert if it was present before and missing after:
import pandas as pd
raw = pd.Series(["1", "2", "x", None])
num = pd.to_numeric(raw, errors="coerce")
failed = raw.notna() & num.isna()
print(raw[failed])The output is:
2 x
dtype: objectThe mask has two parts:
raw.notna()keeps only the positions where the source had a value.num.isna()keeps only the positions where the converted result is missing.
Both must be true. The None at position 3 is missing in both, so it is not a failure. It was already missing.
Keep the original column until you have checked the mask. If you overwrite df["price"] first, the evidence is gone and you must reload the data.
Looking at whole rows
A list of bad values is useful, but often you need the other columns to decide what to do. Use the mask to select rows from the original DataFrame. When several columns are converted, combine their masks with |.
import pandas as pd
df = pd.DataFrame({
"order_id": [101, 102, 103, 104],
"price": ["$1,200", "$85", "n/a", "12.5.0"],
"date": ["2024-01-05", "2024-02-10", "bad", None],
})
cleaned = df["price"].str.replace(r"[$,]", "", regex=True)
price = pd.to_numeric(cleaned, errors="coerce")
date = pd.to_datetime(df["date"], format="%Y-%m-%d", errors="coerce")
price_bad = cleaned.notna() & price.isna()
date_bad = df["date"].notna() & date.isna()
print(df[price_bad | date_bad])This prints the rows for order 103 and order 104. Order 103 fails on both columns. Order 104 fails only on price, because its date is missing in the source rather than invalid.
Note that the price mask is built from cleaned, not from df["price"]. Both choices are valid, but they answer different questions:
- Comparing with
cleanedasks "which values could not be parsed after my cleaning?" This is usually what you want. - Comparing with
df["price"]gives the same positions here, but shows the original text when you print it, such as"$1,200"rather than"1200".
Select the failing values from whichever column you want to see.
Summarizing the failures
On a large column, printing every failure is not practical. Count the distinct bad values instead, so a handful of repeated patterns stand out:
import pandas as pd
raw = pd.Series(["10", "n/a", "20", "n/a", "N/A", "-", "30", "-", "-"])
num = pd.to_numeric(raw, errors="coerce")
failed = raw.notna() & num.isna()
print(failed.sum(), "of", len(raw), "failed")
print(raw[failed].value_counts())Here the counts show - three times, n/a twice and N/A once. All three are placeholders for "no value". That points to a fix at the source: pass na_values=["n/a", "N/A", "-"] to read_csv, or replace them before converting. Once you do, they are treated as missing from the start and no longer count as failures.
The counts also show when a failure is a real data problem. A value like "12.5.0" appearing once is a typo. A value like "1.200,50" appearing hundreds of times is a different number format, and cleaning rules will fix it in bulk.
Choosing an errors setting
pd.to_numeric and pd.to_datetime take an errors argument. The two settings you should use are:
| Setting | On a bad value | Use when |
|---|---|---|
| `"raise"` (default) | Raises an exception | The data should be clean and a bad value is a bug |
| `"coerce"` | Replaces it with `NaN` or `NaT` | You expect some bad values and will inspect them |
With "raise", the exception tells you about the first problem only:
import pandas as pd
try:
pd.to_numeric(pd.Series(["1", "x", "y"]), errors="raise")
except ValueError as err:
print(err)The message names the first value that failed and its position. It does not mention "y". That is why "raise" is a poor tool for finding all the failures, even though it is a good guard in a pipeline where nothing should fail.
A third setting, errors="ignore", returns the input unchanged if anything fails. It is deprecated in recent pandas versions, and it hides the problem you are trying to find, so avoid it.
Turning the check into a guard
If you run the same conversion on every new file, put the check in a function. The function converts, measures the failure share, and stops if it is above a limit you set:
import pandas as pd
def to_numeric_checked(raw, max_bad_share=0.0):
num = pd.to_numeric(raw, errors="coerce")
failed = raw.notna() & num.isna()
share = failed.mean()
if share > max_bad_share:
examples = raw[failed].unique()[:5].tolist()
raise ValueError(
f"{failed.sum()} of {len(raw)} values failed "
f"({share:.1%}); examples: {examples}"
)
return num
good = pd.Series(["1", "2", None])
print(to_numeric_checked(good).tolist())
bad = pd.Series(["1", "2", "x", "y"])
try:
to_numeric_checked(bad)
except ValueError as err:
print(err)The first call returns [1.0, 2.0, nan]. The missing value is not counted as a failure. The second call raises an error that reports the count, the percentage and up to five example values.
Setting max_bad_share=0.0 means "any failure is an error", which is the strict default. Raising it, for example to 0.01, accepts up to 1% bad values. Do that only when you have looked at what the bad values are.
The same structure works for dates. Replace pd.to_numeric with pd.to_datetime(raw, format=..., errors="coerce") and the mask logic is unchanged.
Edge cases
Strings that parse to NaN
Some strings are valid input for pd.to_numeric but still produce a missing result. The string "NaN" parses to NaN, and "inf" parses to infinity. Because raw.notna() is true for the string "NaN" while num.isna() is also true, the mask flags it as a failure even though the parse worked. Look at the flagged values before treating them as errors.
Blank strings
Empty strings and strings of spaces are not missing in the raw column, since notna() is true for them. They usually end up in the failure mask, which is useful: it shows you that the file uses blanks rather than true missing values. Decide whether to strip them, replace them with None, or leave them as failures.
Values that parse but are wrong
The mask only finds values that could not be parsed. It cannot find values that parsed to something you did not intend. Two common cases:
- A date format that matches but reads the day and month the wrong way round. With
format="%d/%m/%Y"the text"03/04/2024"is read as 3 April. If the file actually uses month first, it is read wrongly with no failure at all. - A number that is legal but implausible, such as
-999used as a missing-value code.
After checking for failures, also run describe() or check min() and max() for the column, and compare the dates against a range you know to be valid.
Dates outside the supported range
With errors="coerce", a date that falls outside the range of the datetime64[ns] type, roughly the years 1678 to 2262, becomes NaT. A placeholder such as "1000-01-01" or "9999-12-31" is therefore reported as a failure. The mask catches it, which is the behavior you want here.
Failures with astype
astype does not coerce. Calling astype(int) on a column that holds text that is not a number, or on a float column that contains NaN, raises an exception. That makes astype a strict check by itself, but it stops at the first problem. When you need the full list of bad values, use pd.to_numeric(..., errors="coerce") and the mask first, then call astype on the cleaned result.
Summary of the workflow
- Clean the strings you know about, as in the earlier chapters.
- Convert with
errors="coerce"into a new variable. - Build the mask
raw.notna() & converted.isna(). - Look at the failing values, count them with
value_counts(), and view the rows they come from. - Fix patterns in the cleaning step and rerun, or decide that the remaining failures should be missing.
- Check ranges for values that parsed but look wrong.
- Assign the converted column back.
Exercise
A Series is raw = pd.Series(["5", "7", "seven", None, "9.5", "NA"]). Write code that converts it with pd.to_numeric(..., errors="coerce") and prints only the values that failed to convert. Which values does it print, and why is the None not among them?
Show answer
Code: num = pd.to_numeric(raw, errors="coerce"), then failed = raw.notna() & num.isna(), then print(raw[failed]). It prints "seven" (position 2) and "NA" (position 5). The None is missing in the raw Series as well as in the result, so raw.notna() is False there and the mask excludes it. The value "9.5" parses to 9.5 and is not a failure.
Exercise
You run a nightly job that converts an "amount" column and must not silently drop bad values. Name two ways to make the job stop when a value fails to convert, and say which gives you the complete list of bad values.
Show answer
One way is pd.to_numeric(raw, errors="raise"), which stops with an exception but names only the first bad value. The other is to convert with errors="coerce", build the mask raw.notna() & num.isna(), and raise an error if failed.any() is True. The second way gives the complete list, because the mask marks every failing position and you can include raw[failed].unique() in the error message.