Sub topic 7
Finding the values that failed to convert
This chapter assumes you can build a DataFrame, select rows with a boolean mask, and call pd.to_numeric and pd.to_datetime as shown in the earlier chapters.
Why failures are easy to miss
With errors="coerce", pandas replaces every value it cannot parse with a missing marker: NaN for numbers and NaT for datetimes. The conversion succeeds and no warning appears. The bad values are gone, and the column looks like any other column with gaps.
The default, errors="raise", behaves differently. It stops at the first bad value, which is useful for locating one problem but not for listing all of them.
| `errors` setting | Behavior on a bad value | Use it to |
|---|---|---|
| `"raise"` (default) | Raises `ValueError` | Fail fast when bad data is not expected |
| `"coerce"` | Replaces the value with `NaN` or `NaT` | Convert the column, then inspect the failures |
The comparison pattern
A value failed to convert if the original was not missing but the converted value is. Both checks are needed. Without raw.notna(), values that were already missing would be reported as failures.
import pandas as pd
df = pd.DataFrame({
"id": [101, 102, 103, 104],
"price": ["12.50", "n/a", "9,99", None],
})
df["price_num"] = pd.to_numeric(df["price"], errors="coerce")
failed = df["price_num"].isna() & df["price"].notna()
print(df[failed])The output lists rows 102 and 103. Row 104 holds a genuine missing value, so it is not reported. Keeping id in the output lets you trace each bad value back to its source record.
The same check for dates
The pattern works the same way for pd.to_datetime. Pass an explicit format so that a value in the wrong layout is reported as a failure instead of being guessed.
import pandas as pd
dates = pd.Series(["2024-01-05", "2024-13-01", "bad", None, "bad"])
parsed = pd.to_datetime(dates, format="%Y-%m-%d", errors="coerce")
failed = parsed.isna() & dates.notna()
print(failed.sum())
print(dates[failed].value_counts())Here 2024-13-01 has a month 13, so it fails. The count is 3. Calling value_counts() on the failing values groups repeats, so a column with 10,000 failures caused by the same placeholder (such as "bad" or "TBD") reduces to a short list.
Using raise to find the first offender
When you only need to know whether any value is bad, leave errors at its default and catch the exception.
import pandas as pd
raw = pd.Series(["1", "2", "x", "4"])
try:
pd.to_numeric(raw)
except ValueError as err:
print(err)The message names the offending value and its position. This is fine as a quick check, but it reports only one failure per run.
What to do with the failures
Once you have the list, decide how to handle each group of failures.
- If the values follow a pattern, such as a currency symbol or a comma used as a decimal mark, extend your string cleaning and convert again from the raw column.
- If the values are placeholders like
"n/a", leaving them as missing is usually correct. - If the values are real data errors, save the failing rows to a file or log so someone can correct them at the source.
Always convert from the raw column, not from the already coerced one. That is why the first example writes to a new column, price_num, instead of overwriting price. Once you overwrite, the original text is lost and you can no longer tell why a value is missing.
Exercise
Given raw = pd.Series(["5", "six", None, "7"]) and num = pd.to_numeric(raw, errors="coerce"), write an expression that returns only the values that failed to convert. Which values does it return?
Show answer
raw[num.isna() & raw.notna()]. It returns only "six" (index 1). The None at index 2 is missing in both series, so raw.notna() excludes it.