Python Practice › Pandas Programs › Program 11

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.

Advertisement
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

  1. 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 3

errors="coerce" turns values that are not numbers into NaN instead of raising an error.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More pandas programs

← All 95 Pandas Programs