Sub topic 5
Parsing numbers with pd.to_numeric
This chapter assumes you can build a DataFrame and select columns. It also assumes you know what object columns are and how astype behaves, both covered earlier in this tutorial. Here you will learn how pd.to_numeric turns text into numbers, what its errors setting does, and where it can quietly lose data.
What pd.to_numeric does
pd.to_numeric takes a scalar, list, Series, or other array-like and converts it to a numeric dtype. For a Series of strings, it parses each string as a number and picks the smallest general type that fits:
- If every value is a whole number, the result is
int64. - If any value has a decimal part or is missing, the result is
float64.
import pandas as pd
ints = pd.to_numeric(pd.Series(["3", "5", "7"]))
floats = pd.to_numeric(pd.Series(["3", "5.5", "7"]))
with_gap = pd.to_numeric(pd.Series(["3", None, "7"]))
print(ints.dtype) # int64
print(floats.dtype) # float64
print(with_gap.dtype) # float64The last line surprises many people. A missing value is NaN, which is a float, so one gap pushes the whole column to float64. A later section shows how to keep integers.
How it differs from astype
astype("float64") and pd.to_numeric both parse strings, but they differ in two ways.
| Feature | `astype(float)` | `pd.to_numeric` |
|---|---|---|
| Handles unparseable text | Always raises `ValueError` | Choice of `raise` or `coerce` |
| Picks the dtype | You name it | Chooses int or float for you |
| Downcasting | No | `downcast=` option |
| Works on a whole DataFrame | Yes | One column or Series at a time |
Use astype when the data is already clean and you know the target type. Use pd.to_numeric when some values may not parse and you want control over what happens to them.
Choosing the errors setting
The errors argument decides what happens to a value that cannot be parsed.
errors="raise"is the default. The first bad value raises aValueError.errors="coerce"replaces each bad value withNaN.
s = pd.Series(["10", "20", "thirty"])
try:
pd.to_numeric(s)
except ValueError as exc:
print("raised:", exc)
print(pd.to_numeric(s, errors="coerce"))The first call fails with a message that names the bad string and its position. The second returns 10.0, 20.0, NaN.
A third option, errors="ignore", returned the input unchanged when parsing failed. It is deprecated since pandas 2.2 because it hides failures, and the type of the result depended on the data. Do not use it in new code. If you want the original on failure, wrap the call in try/except.
Cleaning text before parsing
pd.to_numeric accepts plain numeric text, including a leading sign, decimals, and scientific notation such as "1e3". It does not accept currency symbols, thousands separators, percent signs, or units. Clean those first with the .str methods.
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"])The regular expression [$,] matches either a dollar sign or a comma. Result: 1200.0, 85.0, NaN, dtype float64.
Accounting negatives
Finance exports often write negatives in parentheses. Convert them to a minus sign before parsing:
prices = pd.Series(["$1,200", "$85", "n/a", "(40)"])
clean = (
prices.str.replace(r"[$,]", "", regex=True)
.str.replace(r"^\((.*)\)$", r"-\1", regex=True)
)
print(pd.to_numeric(clean, errors="coerce"))The second replacement captures whatever is inside the parentheses and writes it back with a leading minus. The result is 1200.0, 85.0, NaN, -40.0.
Decimal commas
Many European exports use . for thousands and , for decimals. Remove the dots, then turn the comma into a point. Use regex=False so that . is treated as a literal dot, not "any character".
eu = pd.Series(["1.234,56", "78,9"])
fixed = (
eu.str.replace(".", "", regex=False)
.str.replace(",", ".", regex=False)
)
print(pd.to_numeric(fixed))This prints 1234.56 and 78.9. Do this only when you know the whole column uses one convention. In a mixed column, "1,200" could mean twelve hundred or one point two.
Finding the values that failed
The safe pattern is to coerce, then compare against the original. A value failed if the result is NaN but the input was not missing.
raw = pd.Series(["1", "2", "x", None])
num = pd.to_numeric(raw, errors="coerce")
bad = raw[num.isna() & raw.notna()]
print(bad)This prints only the row with "x", with its index label. The genuine None is not reported because it was already missing.
There is a catch: strings such as "nan" and "NaN" parse successfully to NaN. Those rows will not be flagged by the check above, which is usually what you want, since they are explicit missing markers. If you also want to treat "n/a", "-", or "missing" as expected missing values, list them and exclude them from the report:
raw = pd.Series(["10", "n/a", "-", "4O", None])
known_missing = {"n/a", "-"}
num = pd.to_numeric(raw, errors="coerce")
unexpected = raw[num.isna() & raw.notna() & ~raw.isin(known_missing)]
print(unexpected)Only "4O" is reported. A check like this turns a silent data loss into an explicit list you can fix, log, or use to stop the pipeline.
Keeping integers when values are missing
A column of whole numbers with gaps becomes float64. That is harmless for many tasks, but it turns IDs and counts into 3.0 and 5.0. Two options keep them as integers.
s = pd.Series(["1", "2", None])
as_float = pd.to_numeric(s)
print(as_float.dtype) # float64
as_int = as_float.astype("Int64")
print(as_int.dtype) # Int64
direct = pd.to_numeric(s, dtype_backend="numpy_nullable")
print(direct.dtype) # Int64Int64 with a capital I is the nullable integer dtype. It stores missing values as <NA> and keeps the rest as true integers. The dtype_backend argument exists in pandas 2.0 and later and does the conversion in one step.
The cast from float to Int64 fails if any value has a fractional part, for example 2.5. When that happens, either round deliberately first or keep float64.
Edge cases that cause bugs
- Leading zeros disappear.
"007"parses to7. Zip codes, phone numbers, and account IDs are labels, not quantities. Keep them as strings. - Very large integers. Numbers above the
int64range cannot be stored asint64. They may becomeuint64or lose precision asfloat64. Treat long identifiers as strings. - Floating-point precision.
"0.1"becomes the nearest binary float, so sums can differ from decimal arithmetic in the last digits. For money, consider storing integer cents or using Python'sdecimalmodule. - Special words.
"inf","-inf", and"nan"parse successfully. Check forinfwithnp.isinfif it would be a problem downstream. - Mixed types. A column that holds Python numbers and strings together is handled element by element. This works, but the
.straccessor does not, as noted above. - Whole DataFrames.
pd.to_numeric(df)is not supported. Usedf[cols].apply(pd.to_numeric, errors="coerce")for several columns, and assign the result back withdf[cols] = ....
df = pd.DataFrame({
"a": ["1", "2", "x"],
"b": ["4.5", "5.5", "6.5"],
})
cols = ["a", "b"]
df[cols] = df[cols].apply(pd.to_numeric, errors="coerce")
print(df.dtypes)Column a ends up as float64 because of the NaN, and b as float64 because of its decimals.
Common mistakes
- Parsing before cleaning.
pd.to_numeric(df["price"])on"$1,200"raises an error. Clean first. - Forgetting
regex=True. In current pandas versionsstr.replacetreats the pattern as a literal string by default, sor"[$,]"would match nothing. Writeregex=Trueexplicitly. - Not assigning the result.
pd.to_numeric(df["qty"])returns a new Series. The column is unchanged until you assign it back. - Coercing without checking. Count failures with
num.isna().sum()before and after the conversion. The numbers should differ only by the failures you expect. - Expecting integers after coercion. One
NaNmakes the result float. UseInt64when integer values matter.
Exercise
A column "units" holds the strings ["12", "7", "1,050", "none", None]. Write the steps to get a numeric column that keeps whole numbers, and say which rows you would report as unexpected failures if "none" is a known missing marker.
Show answer
Remove commas with units.str.replace(",", "", regex=False), then call pd.tonumeric(..., errors="coerce") and cast with .astype("Int64") (or pass dtypebackend="numpy_nullable"). The result is 12, 7, 1050, <NA>, <NA>. Compare with the original using num.isna() & raw.notna() & ~raw.isin({"none"}). That gives no rows, since "none" is a known marker and None was already missing, so nothing unexpected failed.
Exercise
Why does pd.to_numeric(pd.Series(["1", "2", None])) return float64 rather than int64, and how do you keep integers?
Show answer
The missing value becomes NaN, which only exists as a float, so the whole column is float64. Cast the result with .astype("Int64") or pass dtypebackend="numpynullable" to get a nullable integer column that stores the gap as <NA>.