import pandas as pd
import numpy as np
from datetime import datetime
def clean_csv_data(
input_file,
output_file=None,
column_mappings=None,
na_values=['na', 'n/a', 'nan', 'null', '-', '']
):
"""
Detects and corrects common data inconsistencies in a CSV file.
Args:
input_file (str): Path to the input CSV file.
output_file (str, optional): Path to save the cleaned CSV. Defaults to None.
column_mappings (dict, optional): Dictionary to map inconsistent values.
Format: {'column_name': {'bad_value': 'correct_value'}}
na_values (list): List of strings to interpret as NaN/Null.
Returns:
pd.DataFrame: The cleaned DataFrame.
"""
print(f"--- Starting Cleaning Process for {input_file} ---")
try:
# 1. Load the Data
# encoding='utf-8-sig' handles BOM (Byte Order Mark) common in Excel exports
df = pd.read_csv(input_file, na_values=na_values, encoding='utf-8-sig')
print(f"Loaded {len(df)} rows and {len(df.columns)} columns.")
except Exception as e:
print(f"Error loading file: {e}")
return None
# ---------------------------------------------------------
# 2. Clean Column Names (Remove spaces, special chars, lower case)
# ---------------------------------------------------------
# Strip leading/trailing spaces, convert to lowercase, replace spaces with underscores
df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('[^A-Za-z0-9_]+', '', regex=True)
print("Standardized column headers.")
# ---------------------------------------------------------
# 3. Handle Whitespace and Casing for String Columns
# ---------------------------------------------------------
# Select only object (string) type columns
str_cols = df.select_dtypes(include=['object']).columns
for col in str_cols:
# Strip whitespace and convert to lowercase for consistency
# We apply this generally to fix issues like " Python " vs "python"
df[col] = df[col].astype(str).str.strip().str.lower()
# Convert "nan" strings back to actual NaN objects (result of astype(str))
df[col] = df[col].replace('nan', np.nan)
print("Stripped whitespace and standardized casing on text columns.")
# ---------------------------------------------------------
# 4. Type Conversion & Date Parsing
# ---------------------------------------------------------
for col in df.columns:
# Attempt to convert to numeric (int/float)
# coerce turns errors into NaN, so we don't crash if data is mixed
if df[col].dtype == 'object':
# Try numeric conversion
numeric_converted = pd.to_numeric(df[col], errors='coerce')
# If converting to numeric didn't lose data (create new NaNs), keep it
# This logic is basic; strict pipelines might force types.
if numeric_converted.notna().sum() >= df[col].notna().sum() * 0.8: # Heuristic: if 80% works
df[col] = numeric_converted
# Attempt to parse dates (Pandas often does this automatically, but good to be explicit)
# Note: In a real scenario, ensure you don't accidentally convert IDs to dates.
if df[col].dtype == 'object':
try:
# Simple check for common date separators
if df[col].astype(str).str.contains('/|-').any():
df[col] = pd.to_datetime(df[col], errors='coerce')
except:
pass
# ---------------------------------------------------------
# 5. Custom Value Mapping (Correcting Categorical Typos)
# ---------------------------------------------------------
if column_mappings:
for col, mapping in column_mappings.items():
if col in df.columns:
# Ensure mapping values are also lowercase to match our cleaning in Step 3
# unless specific casing is desired.
clean_mapping = {k.lower(): v for k, v in mapping.items()}
df[col] = df[col].map(lambda x: clean_mapping.get(x, x) if pd.notna(x) else x)
print(f"Applied custom mapping to column: {col}")
# ---------------------------------------------------------
# 6. Deduplication
# ---------------------------------------------------------
original_len = len(df)
df = df.drop_duplicates()
if len(df) < original_len:
print(f"Removed {original_len - len(df)} duplicate rows.")
# ---------------------------------------------------------
# 7. Output
# ---------------------------------------------------------
if output_file:
df.to_csv(output_file, index=False)
print(f"Cleaned data saved to: {output_file}")
print("--- Cleaning Complete ---")
return df
# ==========================================
# Example Usage
# ==========================================
# 1. Create a dummy dirty CSV file for demonstration
dirty_data = """ID, Name, Join Date, Country, Status
1, John Doe, 2021-01-01, USA, Active
2, Jane Smith, 2021-02-15, USA, active
3, Bob, 2021-03-30, U.S.A., Inactive
4, Alice, N/A, Canada, Active
5, Chris, 2021-05-20, USA, ACTIVE
6, John Doe, 2021-01-01, USA, Active
7, 12345, 2021-06-01, UK, Pending
"""
with open("dirty_data.csv", "w") as f:
f.write(dirty_data)
# 2. Define mapping rules to fix inconsistent categorical data
# E.g., "U.S.A." should become "USA", "active" -> "Active"
mappings = {
'country': {
'u.s.a.': 'USA',
'us': 'USA'
},
'status': {
'active': 'Active',
'inactive': 'Inactive'
}
}
# 3. Run the cleaner
cleaned_df = clean_csv_data(
input_file="dirty_data.csv",
output_file="cleaned_data.csv",
column_mappings=mappings
)
# 4. Display result
if cleaned_df is not None:
print("\nPreview of Cleaned Data:")
print(cleaned_df.head())