Sub topic 5
Parsing numbers with pd.to_numeric
This chapter assumes you can build a DataFrame, select a column, and have already checked dtypes with df.dtypes. You should also know that text-based columns have dtype object (or string).
What pd.to_numeric does
pd.to_numeric converts a Series of text, or mixed values, into numbers. It chooses int64 when every value is a whole number. It chooses float64 when there are decimals or missing values.
import pandas as pd
s = pd.Series(["3", "5", "7"])
print(pd.to_numeric(s).dtype)This prints int64. Unlike astype, pd.to_numeric has an errors option that controls what happens when a value cannot be parsed.
Choosing the errors setting
| Setting | Behavior on an unparseable value |
|---|---|
| `"raise"` (default) | Raises a `ValueError` and stops. |
| `"coerce"` | Replaces the value with `NaN`. |
Older code may use errors="ignore", which returns the input unchanged. pandas 2.2 deprecated it, so avoid it in new code.
Use "raise" while you explore, because it stops at the first bad value. Switch to "coerce" only when you plan to check what was lost.
Clean first, then convert
pd.to_numeric does not understand currency symbols or thousands separators. A value like "$1,200" fails, so remove those characters first with the .str accessor.
import pandas as pd
df = pd.DataFrame({"price": ["$1,200", "$85", "n/a"]})
df["price"] = pd.to_numeric(
df["price"].str.replace(r"[$,]", "", regex=True),
errors="coerce",
)
print(df["price"])
print(df["price"].dtype)The regular expression [$,] matches either a dollar sign or a comma. After cleaning, "1200" and "85" parse as numbers, and "n/a" becomes NaN. The column is float64 because NaN is a float value.
<br>
Do not lose values silently
With errors="coerce", a typo like "x" becomes NaN, which looks the same as a value that was already missing. To separate the two cases, compare the result with the original. A value that was present in the original but is NaN after conversion failed to parse.
import pandas as pd
raw = pd.Series(["1", "2", "x", None])
num = pd.to_numeric(raw, errors="coerce")
bad = raw[num.isna() & raw.notna()]
print(bad)The output shows only the row with "x". The None is not listed, because it was already missing. You can now correct the source data or add a cleaning rule, then run the conversion again.
Integers and missing values
A column of whole numbers that contains NaN ends up as float64, because the classic NumPy int64 type cannot hold missing values. If you want to keep integer values, convert to the nullable Int64 dtype after parsing.
import pandas as pd
qty = pd.Series(["3", "5", None])
qty = pd.to_numeric(qty).astype("Int64")
print(qty)The result shows 3, 5 and <NA>, with dtype Int64. Note the capital I. The later chapter on nullable dtypes explains this type in detail.
Common errors
- ValueError: Unable to parse string. The default
errors="raise"found a value such as"$85". Clean the text first, or use"coerce"and then inspect the failures. - AttributeError: Can only use .str accessor with string values. The column is already numeric, or is mixed in a way that has no
.straccessor. Check the dtype before you clean. - Everything became NaN. Your cleaning step probably removed too much, or a different separator is used. Examples are a decimal comma, as in
"1.200,50", or a trailing space. Print a few raw values and look at them. - Wrong decimal handling.
pd.to_numerichas no decimal-separator option. Replace the separators yourself before converting.
Exercise
A column "amount" holds the strings "12.5", "1,000", "N/A" and "7". You run pd.to_numeric(df["amount"], errors="coerce"). Which values become NaN, and what should you do first to avoid losing a real value?
Show answer
"N/A" and "1,000" both become NaN. "N/A" is truly not a number, but "1,000" is a real value that failed because of the thousands separator. Remove the comma first with df["amount"].str.replace(",", "", regex=False), then call pd.to_numeric with errors="coerce". Only "N/A" is then NaN.