Python Practice › Pandas Programs › Program 11
Convert a Series to numbers
Write a pandas program to convert a mixed Series to numbers, turning text into NaN.
Input
["54", "27.90", "sqa", "33.33", "tools"]
Output
0 54.00 1 27.90 2 NaN 3 33.33 4 NaN dtype: float64
Approach
pd.to_numeric(..., errors="coerce").
Solution
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 3
errors="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.