The user is asking for a Python program to detect and remove outliers from a dataset. I need to decide if the dataset is a numerical vector or a pandas DataFrame. I think it’d be beneficial to use the IQR method or Z-score for robustness. While I could ask for clarifications, I’ll proceed with a script that loads a CSV file, identifies outliers using the IQR method, and summarizes the results. I should also assume common libraries like pandas and numpy are allowed.Drafting outlier removal program
I’m defining a function to remove outliers using the IQR method in Python. The function takes a DataFrame and specific columns to analyze. I'll create a script that reads a CSV file containing the data, identifies numeric columns, and cleans the dataset by removing outliers. It’s a good idea to explain the IQR method briefly and mention alternative methods like the Z-score. I want to keep the focus tight and avoid any distractions in my explanation as I draft this program. Below is a simple, general Python program (using pandas and NumPy) that:
Loads a dataset from a CSV file
Detects outliers in numeric columns using the IQR (Interquartile Range) method
Removes those outliers
Saves the cleaned dataset
You can adapt it as needed.
python
#!/usr/bin/env python3
"""
Detect and remove outliers from a dataset using the IQR method.
Usage (from terminal):
python remove_outliers.py input.csv output_clean.csv
"""
import sys
import pandas as pd
import numpy as np
def detect_outliers_iqr(df, columns=None, k=1.5):
"""
Detect outliers in a DataFrame using the IQR method.
Parameters
----------
df : pd.DataFrame
Input DataFrame.
columns : list or None
Columns to check for outliers. If None, all numeric columns are used.
k : float
IQR multiplier (1.5 is standard; 3.0 for more conservative detection).
Returns
-------
outlier_mask : pd.Series (bool)
True for rows that are outliers in ANY of the selected columns.
"""
if columns is None:
columns = df.select_dtypes(include=np.number).columns
outlier_mask = pd.Series(False, index=df.index)
for col in columns:
q1 = df[col].quantile(0.25)
q3 = df[col].quantile(0.75)
iqr = q3 - q1
lower_bound = q1 - k * iqr
upper_bound = q3 + k * iqr
col_outliers = (df[col] < lower_bound) | (df[col] > upper_bound)
outlier_mask |= col_outliers
return outlier_mask
def main(input_path, output_path, k=1.5):
# 1. Load dataset
df = pd.read_csv(input_path)
# 2. Detect outliers
outlier_mask = detect_outliers_iqr(df, k=k)
n_outliers = outlier_mask.sum()
print(f"Total rows: {len(df)}")
print(f"Outlier rows: {n_outliers}")
print(f"Rows kept: {len(df) - n_outliers}")
# 3. Remove outliers
df_clean = df[~outlier_mask].reset_index(drop=True)
# 4. Save cleaned dataset
df_clean.to_csv(output_path, index=False)
print(f"Cleaned data saved to: {output_path}")
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python remove_outliers.py input.csv output_clean.csv")
sys.exit(1)
input_csv = sys.argv[1]
output_csv = sys.argv[2]
# Optional: change k here if you want a stricter/looser definition of outliers
main(input_csv, output_csv, k=1.5)