Convert a Series to numbers
EasyPandas Programs · 11 of 95
Write a pandas program to convert a mixed Series to numbers, turning text into NaN.
Input["54", "27.90", "sqa", "33.33", "tools"]
Output0 54.00
1 27.90
2 NaN
3 33.33
4 NaN
dtype: float64
Approach
pd.to_numeric(..., errors="coerce").
Solution
Python
import pandas as pds = pd.Series(["54", "27.90", "sqa", "33.33", "tools"])print(pd.to_numeric(s, errors="coerce"))
Output
0 54.00
1 27.90
2 NaN
3 33.33
4 NaN
dtype: float64
Line by line
Line 3errors="coerce" turns values that are not numbers into NaN instead of raising an error.
Learn the concept
New to this topic? Read the lesson, then come back.
More pandas programs
← All 95 Pandas Programs