Editor

Handle Outliers

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

From the lesson: Step 6: Handle Outliers

Outliers are values that are technically valid numbers but make no sense in context. An age of -5 or 150 is a valid integer, but not a valid human age. We need to define reasonable bounds and deal with values outside them.

Read this part of the lesson

Write a function handle_outliers(df) that:

1. Clips the age column to be between 0 and 120 (inclusive)

2. Clips the purchase_total column to be between 0 and 10000

3. Prints how many values were clipped in each column

4. Returns the cleaned DataFrame

To count clipped values, compare the original column to the clipped version before overwriting.

import pandas as pd
def handle_outliers(df):
# Your code here
pass
data = {
'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'age': [28, -5, 150, 35],
'purchase_total': [150.0, 200.0, -50.0, 15000.0]
}
df = pd.DataFrame(data)
cleaned = handle_outliers(df)
print(cleaned.to_string(index=False))

More Data Cleaning Pipeline exercises

All Python exercises · 50 practice problems · Practical Projects quiz