Editor

Handle Missing Values

Intermediate · Write the code · from Build an Automated Data Cleaning Pipeline

From the lesson: Step 2: Identify and Handle Missing Values

Missing data is the most common problem you'll encounter. There are two main strategies: drop the rows with missing values, or fill them with something sensible. The right choice depends on the column and how much data is missing.

Read this part of the lesson

Write a function handle_missing(df) that:

1. Drops rows where name is missing (None/NaN)

2. Drops rows where email is missing

3. Fills missing purchase_total values with 0.0

4. Fills missing signup_date values with "Unknown"

5. Returns the cleaned DataFrame

Then call it and print how many rows remain.

import pandas as pd
def handle_missing(df):
# Your code here
pass
# Test data
data = {
'name': ['Alice', None, 'Charlie', 'Diana'],
'email': ['a@test.com', 'b@test.com', None, 'd@test.com'],
'purchase_total': [100.0, None, 50.0, None],
'signup_date': ['2024-01-01', None, '2024-03-01', None]
}
df = pd.DataFrame(data)
cleaned = handle_missing(df)
print(f'Rows remaining: {len(cleaned)}')
print(cleaned.to_string(index=False))

More Data Cleaning Pipeline exercises

All Python exercises · 50 practice problems · Practical Projects quiz