Pandasdrill

Level 2: Cleaning Exercise 27 of 102

Text to numbers, bad values to NaN

A pandas exercise from Pandasdrill. Solve it with a Python editor in your browser running real pandas, and it is checked the moment you submit.

The task

The `age` column of `survey` is text, and some entries are not numbers at all ("n/a", "unknown" or empty). Convert the column to numbers, with every entry that is not a number turned into NaN, and return it as a Series.

What this exercise teaches

astype(float) stops with an error at the first entry it cannot read. pd.to_numeric with errors="coerce" converts what it can and marks the rest as NaN, so you can count or fill the bad entries afterwards instead of listing every spelling by hand.

A hint if you get stuck

pd.to_numeric converts text to numbers. Its errors argument decides what happens to text that is not a number: "coerce" turns it into NaN.

Try it now, free, no account needed

Your first 8 exercises on Pandasdrill are free. Open it on the practice page, solve it, and get instant feedback with a hint. A free account adds the worked solution; Pro unlocks every exercise, timed mode and the certificate.

Open this exercise

More exercises in Cleaning