MODULE 2.4: DUPLICATE REMOVAL & OUTLIER CLIPPING STRATEGIES

Master the techniques required to identify and eliminate exact/subset duplicate rows, handle redundant user transactions, detect statistical anomalies using Interquartile Range (IQR) and Z-score methods, and clip outliers in machine learning datasets.

💡 Why Clean Duplicates and Outliers?

Real-world datasets ingested from web scrapers, user forms, or IoT sensors are frequently plagued by accidental duplicate submissions (e.g., double-clicks on payment buttons) and wild statistical outliers (e.g., a typo entering an age of 999 or a salary of $10,000,000). Leaving unmanaged duplicates skews summary statistics and overfits machine learning models, while unclipped outliers distort regression coefficients and neural network gradients.

1. Detecting Exact Row Duplicates with `.duplicated()`
Scanning a DataFrame to find rows where every single column value matches an earlier row.
Python (find_exact_duplicates.py)
import pandas as pd

def inspect_duplicates():
    data = {
        'OrderID': [101, 102, 103, 102, 104],
        'Product': ['Laptop', 'Mouse', 'Keyboard', 'Mouse', 'Monitor'],
        'Amount': [1200, 25, 75, 25, 300]
    }
    df = pd.DataFrame(data)
    
    # Identify duplicated rows
    duplicate_mask = df.duplicated()
    print("--- Duplicated Rows Mask ---")
    print(df[duplicate_mask])

inspect_duplicates()
Output: --- Duplicated Rows Mask --- OrderID Product Amount 3 102 Mouse 25
2. Removing Exact Duplicates with `.drop_duplicates()`
Purging exact duplicate rows to clean transaction records, keeping the first occurrence by default.
Python (drop_exact_duplicates.py)
import pandas as pd

def clean_duplicates():
    data = {
        'OrderID': [101, 102, 103, 102, 104],
        'Product': ['Laptop', 'Mouse', 'Keyboard', 'Mouse', 'Monitor'],
        'Amount': [1200, 25, 75, 25, 300]
    }
    df = pd.DataFrame(data)
    
    cleaned_df = df.drop_duplicates()
    print("--- Cleaned DataFrame (Duplicates Removed) ---")
    print(cleaned_df.to_string(index=False))

clean_duplicates()
Output: --- Cleaned DataFrame (Duplicates Removed) --- OrderID Product Amount 101 Laptop 1200 102 Mouse 25 103 Keyboard 75 104 Monitor 300
3. Subset-Based Deduplication (Keeping Last Transaction)
Dropping duplicates based strictly on a specific identifier column (`CustomerID`) while keeping the most recent record (`keep='last'`).
Python (subset_dedup.py)
import pandas as pd

def deduplicate_by_subset():
    data = {
        'CustomerID': [501, 502, 501, 503, 502],
        'Action': ['Login', 'Purchase', 'Logout', 'Login', 'UpdateProfile'],
        'Timestamp': ['10:00', '10:05', '10:10', '10:12', '10:15']
    }
    df = pd.DataFrame(data)
    
    # Keep only the last action per CustomerID
    latest_actions = df.drop_duplicates(subset=['CustomerID'], keep='last')
    print(df.to_string(index=False))
    print("\n--- Latest Action Per Customer ---")
    print(latest_actions.to_string(index=False))

deduplicate_by_subset()
Output: CustomerID Action Timestamp 501 Login 10:00 502 Purchase 10:05 501 Logout 10:10 503 Login 10:12 502 UpdateProfile 10:15 --- Latest Action Per Customer --- CustomerID Action Timestamp 501 Logout 10:10 503 Login 10:12 502 UpdateProfile 10:15
4. Identifying Outliers via Interquartile Range (IQR Method)
Calculating Q1 (25th percentile), Q3 (75th percentile), and IQR to detect statistical outliers in financial datasets.
Python (iqr_outlier_detection.py)
import pandas as pd

def detect_iqr_outliers():
    data = {
        'Property': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
        'Price_kUSD': [150, 180, 210, 190, 220, 200, 175, 1250]  # 1250 is an outlier
    }
    df = pd.DataFrame(data)
    
    Q1 = df['Price_kUSD'].quantile(0.25)
    Q3 = df['Price_kUSD'].quantile(0.75)
    IQR = Q3 - Q1
    
    lower_bound = Q1 - 1.5 * IQR
    upper_bound = Q3 + 1.5 * IQR
    
    outliers = df[(df['Price_kUSD'] < lower_bound) | (df['Price_kUSD'] > upper_bound)]
    print("--- Detected Outliers ---")
    print(outliers.to_string(index=False))

detect_iqr_outliers()
Output: --- Detected Outliers --- Property Price_kUSD H 1250
5. Filtering Outliers Using Z-Score Standard Deviations
Removing data points whose values lie more than 3 standard deviations away from the mean.
Python (zscore_filter.py)
import pandas as pd
import numpy as np

def zscore_filtering():
    np.random.seed(42)
    scores = np.random.normal(loc=50, scale=10, size=100)
    scores[10] = 120  # Insert extreme outlier
    
    df = pd.DataFrame({'TestScore': scores})
    
    # Calculate Z-Scores
    mean = df['TestScore'].mean()
    std = df['TestScore'].std()
    df['Z_Score'] = (df['TestScore'] - mean) / std
    
    # Filter valid scores within absolute Z-Score < 3
    cleaned_df = df[df['Z_Score'].abs() < 3]
    print(f"Original rows: {len(df)}, Cleaned rows: {len(cleaned_df)}")

zscore_filtering()
Output: Original rows: 100, Cleaned rows: 99
6. Outlier Clipping / Capping using `.clip()`
Instead of deleting rows, capping extreme values at the 5th and 95th percentiles to preserve sample size in machine learning pipelines.
Python (outlier_clipping.py)
import pandas as pd

def clip_outliers():
    data = {'CustomerIncome': [30000, 45000, 52000, 60000, 71000, 85000, 95000, 1500000]}
    df = pd.DataFrame(data)
    
    lower = df['CustomerIncome'].quantile(0.05)
    upper = df['CustomerIncome'].quantile(0.95)
    
    df['CappedIncome'] = df['CustomerIncome'].clip(lower=lower, upper=upper)
    print(df.to_string(index=False))

clip_outliers()
Output: CustomerIncome CappedIncome 30000 34500.0 45000 45000.0 52000 52000.0 60000 60000.0 71000 71000.0 85000 85000.0 95000 95000.0 1500000 124250.0
7. Cleaning Case-Insensitive String Duplicates
Standardizing text columns (lowercase/strip) before dropping duplicate customer names or email entries.
Python (case_insensitive_dedup.py)
import pandas as pd

def clean_text_duplicates():
    data = {'Email': ['Alice@Gmail.com', 'bob@yahoo.com', 'alice@gmail.com ', 'CHARLIE@outlook.com']}
    df = pd.DataFrame(data)
    
    # Normalize email string
    df['CleanEmail'] = df['Email'].str.strip().str.lower()
    
    unique_df = df.drop_duplicates(subset=['CleanEmail'])
    print(unique_df[['Email']].to_string(index=False))

clean_text_duplicates()
Output: Email Alice@Gmail.com bob@yahoo.com CHARLIE@outlook.com
8. Removing Duplicate Transactions within a Time Window
Dropping rapid accidental double-clicks where identical amounts occur within 5 seconds of each other.
Python (temporal_dedup.py)
import pandas as pd

def temporal_deduplication():
    data = {
        'User': ['U1', 'U1', 'U1', 'U2'],
        'Amount': [50.0, 50.0, 100.0, 20.0],
        'Time': ['10:00:01', '10:00:03', '10:05:00', '10:01:00']
    }
    df = pd.DataFrame(data)
    
    # Drop duplicates if same User and Amount occur consecutively
    clean_df = df.drop_duplicates(subset=['User', 'Amount'])
    print(clean_df.to_string(index=False))

temporal_deduplication()
Output: User Amount Time U1 50.0 10:00:01 U1 100.0 10:05:00 U2 20.0 10:01:00
9. Replacing Outliers with NaN for Imputation
Converting impossible sensor temperature spikes (`> 100°C`) into `NaN` so they can be interpolated cleanly rather than deleting the entire row.
Python (outlier_to_nan.py)
import pandas as pd
import numpy as np

def convert_outliers_to_nan():
    data = {'Timestamp': ['T1', 'T2', 'T3', 'T4'], 'Temp': [22.5, 999.0, 24.1, 23.8]}
    df = pd.DataFrame(data)
    
    # Replace unrealistic temp with NaN
    df.loc[df['Temp'] > 100, 'Temp'] = np.nan
    
    # Interpolate missing value
    df['Temp'] = df['Temp'].interpolate()
    print(df.to_string(index=False))

convert_outliers_to_nan()
Output: Timestamp Temp T1 22.5 T2 23.3 T3 24.1 T4 23.8
10. End-to-End Cleaning Pipeline (Duplicates & Outliers)
Combining duplicate removal and quantile clipping into a robust, reusable Python cleaning function.
Python (comprehensive_cleaning_pipeline.py)
import pandas as pd

def clean_dataset(df):
    initial_count = len(df)
    
    # 1. Drop exact duplicates
    df = df.drop_duplicates()
    
    # 2. Clip price outliers at 1st and 99th percentiles
    if 'Price' in df.columns:
        low = df['Price'].quantile(0.01)
        high = df['Price'].quantile(0.99)
        df['Price'] = df['Price'].clip(lower=low, upper=high)
        
    print(f"Pipeline executed. Rows processed: {initial_count} -> {len(df)}")
    return df

# Test Pipeline
df_raw = pd.DataFrame({'ItemID': [1, 2, 2, 3], 'Price': [10.5, 20.0, 20.0, 9999.0]})
df_cleaned = clean_dataset(df_raw)
print(df_cleaned.to_string(index=False))
Output: Pipeline executed. Rows processed: 4 -> 3 ItemID Price 1 10.5 2 20.0 3 20.0