import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Sample dataset generation (with outliers)
# Replace this section with: df = pd.read_csv('your_dataset.csv') for your own data
np.random.seed(42)
data = np.random.normal(100, 15, 1000)
data = np.append(data, [200, 250, 20, -10, 300]) # Adding some outliers
df = pd.DataFrame({'values': data})
print("Sample dataset created with shape:", df.shape)
print(df.head())
def detect_outliers_iqr(df, column):
"""
Detect outliers using the Interquartile Range (IQR) method.
Parameters:
- df: pandas DataFrame
- column: str, name of the column to check for outliers
Returns:
- outliers_df: DataFrame containing the outliers
- lower_bound, upper_bound: float, the IQR bounds
"""
Q1 = df[column].quantile(0.25)
Q3 = df[column].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
outliers_mask = (df[column] < lower_bound) | (df[column] > upper_bound)
outliers_df = df[outliers_mask].copy()
outliers_df['outlier_reason'] = np.where(df.loc[outliers_mask, column] < lower_bound,
'Below lower bound', 'Above upper bound')
print(f"\nIQR Bounds for '{column}': Lower = {lower_bound:.2f}, Upper = {upper_bound:.2f}")
print(f"Number of outliers detected: {len(outliers_df)}")
return outliers_df, lower_bound, upper_bound
def remove_outliers_iqr(df, column):
"""
Remove outliers from the specified column using IQR method.
Parameters:
- df: pandas DataFrame
- column: str, name of the column to clean
Returns:
- cleaned_df: DataFrame with outliers removed
"""
Q1 = df[column].quantile(0.25)
Q3 = df[column].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
cleaned_mask = (df[column] >= lower_bound) & (df[column] <= upper_bound)
cleaned_df = df[cleaned_mask].copy()
print(f"Original dataset shape: {df.shape}")
print(f"Cleaned dataset shape: {cleaned_df.shape}")
print(f"Outliers removed: {df.shape[0] - cleaned_df.shape[0]} ({100 * (1 - cleaned_df.shape[0]/df.shape[0]):.1f}%)")
return cleaned_df
# Step 1: Detect outliers
outliers_df, lower_bound, upper_bound = detect_outliers_iqr(df, 'values')
print("\nOutliers detected:")
print(outliers_df)
# Step 2: Remove outliers
cleaned_df = remove_outliers_iqr(df, 'values')
# Step 3: Visualization (before and after)
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
# Boxplot: Original
sns.boxplot(data=df, y='values', ax=axes[0, 0])
axes[0, 0].set_title('Original Data - Boxplot')
# Histogram: Original
df['values'].hist(bins=30, ax=axes[0, 1], alpha=0.7, edgecolor='black')
axes[0, 1].axvline(lower_bound, color='red', linestyle='--', label=f'Bounds: [{lower_bound:.1f}, {upper_bound:.1f}]')
axes[0, 1].axvline(upper_bound, color='red', linestyle='--')
axes[0, 1].set_title('Original Data - Histogram')
axes[0, 1].legend()
# Boxplot: Cleaned
sns.boxplot(data=cleaned_df, y='values', ax=axes[1, 0])
axes[1, 0].set_title('Cleaned Data - Boxplot')
# Histogram: Cleaned
cleaned_df['values'].hist(bins=30, ax=axes[1, 1], alpha=0.7, edgecolor='black')
axes[1, 1].set_title('Cleaned Data - Histogram')
plt.tight_layout()
plt.show()
# Optional: Statistics comparison
print("\nDescriptive Statistics Comparison:")
print("Original:")
print(df['values'].describe())
print("\nCleaned:")
print(cleaned_df['values'].describe())
How to Use This Program:
- Run as-is: Uses a sample dataset with normally distributed data + outliers.
- With your own data:
- Replace the sample data generation with
df = pd.read_csv('your_file.csv').
- Specify your column: e.g.,
detect_outliers_iqr(df, 'your_column_name').
- For multiple columns: Loop over columns, e.g.:
for col in df.select_dtypes(include=[np.number]).columns:
print(f"\nProcessing column: {col}")
cleaned_col = remove_outliers_iqr(df, col)
- Customization:
This program uses the robust IQR method (works well for non-normal data), provides detection/removal functions, console output, and visualizations for easy verification. No external files needed!