Editor

The Complete Pipeline

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

From the lesson: Step 8: Build the Complete Pipeline

Now it's time to combine all the cleaning steps into a single reusable function. A good pipeline function takes messy data in, applies each cleaning step in the right order, and returns clean data.

Read this part of the lesson

Write a function clean_data(df) that applies these steps in order:

1. Drop rows where name is missing

2. Standardize name: strip whitespace and convert to title case

3. Standardize email: strip whitespace and convert to lowercase

4. Remove duplicate rows based on name and email

5. Convert age to numeric (coerce errors), fill NaN with median, round and convert to int

6. Clip age between 0 and 120

7. Fill missing purchase_total with 0.0

8. Reset the index (drop=True)

9. Return the cleaned DataFrame

Print the final row count and the cleaned DataFrame.

import pandas as pd
def clean_data(df):
# Step 1: Drop rows with missing name
# Step 2: Standardize name
# Step 3: Standardize email
# Step 4: Remove duplicates
# Step 5: Fix age data type
# Step 6: Clip age outliers
# Step 7: Fill missing purchase_total
# Step 8: Reset index
pass
data = {
'name': ['Alice Smith', ' bob jones ', 'ALICE SMITH', None, 'Charlie Brown'],
'email': ['alice@test.com', 'bob@test.com', 'ALICE@TEST.COM', 'x@test.com', 'charlie@test.com'],
'age': [28, 'thirty', 28, 40, -5],
'purchase_total': [150.0, None, 150.0, 200.0, 75.0]
}
df = pd.DataFrame(data)
cleaned = clean_data(df)
print(f'Clean rows: {len(cleaned)}')
print(cleaned[['name', 'email', 'age']].to_string(index=False))

More Data Cleaning Pipeline exercises

All Python exercises · 50 practice problems · Practical Projects quiz