Editor

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 lesson

Write 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.

import pandas as pd
def fix_data_types(df):
# Your code here
pass
data = {
'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
'age': [28, 'thirty-two', 45, 35, 'N/A'],
'purchase_total': [150.0, '200', None, '89.99', 320.0]
}
df = pd.DataFrame(data)
cleaned = fix_data_types(df)
print(cleaned[['name', 'age']].to_string(index=False))

More Data Cleaning Pipeline exercises

All Python exercises · 50 practice problems · Practical Projects quiz