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 exerciseMore exercises in Cleaning
- Fill missing values in one column
- Drop rows missing a key field
- Convert text to numbers
- Tidy up text with strip and lower
- Search text with str.contains
- Pull numbers out of codes
- Remove duplicate records
- Rename columns and replace a placeholder
- Dates with to_datetime and dt
- Clean messy money text
- Split a column into two
- Fill gaps with interpolate
- Parse dates in day/month/year order
- Recode values with map
- Limit values to a range with clip