Sub topic 2
Parsing Numbers with `pd.to_numeric`
Assume you know basic pandas Series and DataFrames, indexing, and reading CSV files. This chapter uses coercion and validation together: convert messy values, then inspect what did not convert.
Parsing numbers with `pd.to_numeric`
pd.to_numeric parses values into numeric types. Its default, errors="raise", stops at the first invalid value. Use errors="coerce" when you need the whole column converted. Invalid values become NaN, so you can inspect them afterward.
Clean formatting before parsing. Currency symbols and thousands separators are text, not numeric syntax that pandas can always interpret.
import pandas as pd
df = pd.DataFrame({
"price": ["$1,200", "$85", "n/a"],
"qty": ["3", "5", "7"],
"order_date": ["2024-01-05", "2024-02-10", "bad"],
})
raw_price = df["price"]
clean_price = raw_price.str.replace(r"[$,]", "", regex=True)
df["price"] = pd.to_numeric(clean_price, errors="coerce")
df["qty"] = pd.to_numeric(df["qty"], errors="raise")
df["order_date"] = pd.to_datetime(
df["order_date"],
format="%Y-%m-%d",
errors="coerce",
)
print(df)
print(df.dtypes)Parsing dates with `pd.to_datetime`
pd.to_datetime converts text into pandas datetime values. Give format when the input follows a known pattern. It makes the expected layout clear and can prevent ambiguous interpretation.
With errors="coerce", invalid dates become NaT, pandas’ missing datetime value. Use errors="raise" when invalid input means the data file must be rejected.
Finding values that failed to convert
Keep the original Series before conversion. Then compare it with the converted Series. The mask below selects values that were present originally but became missing during conversion.
raw = pd.Series(["1", "2", "x", None])
parsed = pd.to_numeric(raw, errors="coerce")
failed = raw[raw.notna() & parsed.isna()]
print("Failed numeric values:")
print(failed)
raw_dates = pd.Series(["2024-01-05", "bad", None])
parsed_dates = pd.to_datetime(
raw_dates,
format="%Y-%m-%d",
errors="coerce",
)
failed_dates = raw_dates[raw_dates.notna() & parsed_dates.isna()]
print("Failed date values:")
print(failed_dates)This pattern preserves the row index, so you can locate the original records and correct or reject them.
Exercise
Which mask identifies a non-missing string that failed numeric conversion?
Show answer
raw[raw.notna() & parsed.isna()]