Fix Data Types
Intermediate · Write the code · from Build an Automated Data Cleaning Pipeline
From the lesson: Step 4: Fix Data Types
Sometimes columns that should be numbers contain text values. The age column in our dataset has entries like "thirty-two" mixed in with real numbers. We need to convert these to proper numeric types, handling the invalid entries gracefully.
Read this part of the lessonWrite a function fix_data_types(df) that:
1. Converts the age column to numeric (coercing errors to NaN)
2. Converts the purchase_total column to numeric (coercing errors)
3. Fills any NaN values in age with the median of the valid ages
4. Rounds the filled age values to whole numbers (use .round(0)) then converts to int
5. Returns the cleaned DataFrame
Print the age column after cleaning.
More Data Cleaning Pipeline exercises
- Load and Inspect the DataIntermediate
- Handle Missing ValuesIntermediate
- Remove DuplicatesIntermediate
- Standardize Text FieldsIntermediate
- Handle OutliersIntermediate
- Predict the Pipeline OutputIntermediate
- The Complete PipelineIntermediate
All Python exercises · 50 practice problems · Practical Projects quiz