I'm focused on grasping the user's objective: outlier detection and removal in Python. I've broken it down to understand what tools I need. It's looking like pandas will be a critical component for data manipulation.
Decomposing the Solution
I'm now outlining the steps for a Python script. I'm focusing on providing the user with two methods, Z-score and IQR, with clear code examples. I'm planning to introduce the concept of outliers and their removal, followed by a comparison of both methods to allow for optimal usage based on the user's data.
Coding the Examples
I'm now writing and refining the code examples. I've created a sample DataFrame with easily identifiable outliers to make the demonstration clear. The draft includes both the Z-score and IQR methods, complete with data setup and explanations. I'm focusing on ensuring each step is easily understood and reproducible by the user.
Completing the Script
I'm finalizing the structure of the response. I've decided to begin with the IQR method due to its versatility, followed by the Z-score method. A complete, runnable Python script incorporating both approaches is being prepared, accompanied by clear explanations. I'm also including a note about the methods being applicable only to numeric data.
Optimizing Code and Output
I'm now focusing on optimizing the code examples and the overall presentation. I'm adding comments within the code to explain each step thoroughly, making it easier for the user to understand and adapt. I'm also preparing to include a brief note about the limitations of these methods, specifically their applicability to numerical data and the customizability of threshold values. I've decided to add the boxplot visualization as it reinforces the IQR method clearly.
Here are the two most common statistical methods for detecting and removing outliers: the Interquartile Range (IQR) method and the Z-Score method.
Prerequisite
You will need pandas and numpy installed.
bash
pip install pandas numpy scipy
Method 1: The IQR Method (Robust / Most Common)
The Interquartile Range method is excellent for data that may not be perfectly normally distributed. It calculates the "middle 50%" of your data and defines outliers as points that fall significantly below or above that range.
The Logic:
Calculate Q1 (25th percentile) and Q3 (75th percentile).
import pandas as pd
import numpy as np
# 1. Create a sample dataset with obvious outliers
data = {
'Age': [25, 26, 28, 30, 29, 27, 26, 28, 302, 25, 27, -50, 28]
}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
print("-" * 30)
# 2. Calculate Q1, Q3, and IQR
Q1 = df['Age'].quantile(0.25)
Q3 = df['Age'].quantile(0.75)
IQR = Q3 - Q1
# 3. Define Bounds
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
print(f"Lower Bound: {lower_bound}")
print(f"Upper Bound: {upper_bound}")
print("-" * 30)
# 4. Filter the data
# We interpret this as: Keep the data where Age is BETWEEN the bounds
df_cleaned = df[(df['Age'] >= lower_bound) & (df['Age'] <= upper_bound)]
# Alternatively, to see what was dropped:
outliers = df[(df['Age'] < lower_bound) | (df['Age'] > upper_bound)]
print("Cleaned DataFrame:")
print(df_cleaned)
print("\nDetected Outliers:")
print(outliers)
Method 2: The Z-Score Method
This method assumes your data is Normally Distributed (bell curve). It measures how many standard deviations a data point is away from the mean. A standard cutoff is 3, meaning any data point more than 3 standard deviations away is an outlier.
The Logic:
Calculate the Z-score for every data point.
If the absolute value of the Z-score is greater than 3, it is an outlier.
python
import pandas as pd
import numpy as np
from scipy import stats
# 1. Create sample dataset
data = {
'Score': [10, 12, 12, 13, 12, 11, 14, 13, 10, 100, 12, 11]
# 100 is the outlier here
}
df = pd.DataFrame(data)
# 2. Calculate Absolute Z-Scores
# We take the absolute value because we care about distance from mean
# (positive or negative)
z_scores = np.abs(stats.zscore(df['Score']))
print("Z-Scores:")
print(z_scores)
print("-" * 30)
# 3. Define a threshold (usually 3)
threshold = 3
# 4. Filter the data
# Keep rows where all Z-scores are less than the threshold
df_cleaned = df[(z_scores < threshold)]
print("Original DataFrame Size:", df.shape)
print("Cleaned DataFrame Size:", df_cleaned.shape)
print("\nCleaned Data:")
print(df_cleaned)
Which one should I use?
Use IQR: If your data is skewed (not a perfect bell curve) or you have a small dataset. This is the safer, more general approach for tasks like cleaning sensor data, prices, or ages.
Use Z-Score: If you know for a fact that your data follows a Gaussian (Normal) distribution and you want to strictly filter based on standard deviation logic.