Examining Data Inconsistencies
I'm currently focused on the core function. I've been breaking down the process into modules. The design involves robust error handling and flexible cleaning rules. Input format handling is becoming clearer. I'm exploring Pandas and potentially other libraries for performance and efficiency. I'm making sure it's scalable.
Outlining Data Processing Steps
I've just been thinking about the specific steps. It's becoming clearer: first load the data, then find and fix any problems. Finally, I'll save or give back the clean data. Python will be my main language, and Pandas seems like the right tool, maybe with NumPy for some parts.
Refining Function Design
I'm now diving into the finer points of the function's structure. Modularity is key, so I'm leaning toward a main function that calls helper functions. I'm also planning optional parameters for flexibility. I'm drafting the function signature now, which will handle input and output paths and cleaning strategies. This should be a general purpose function that is robust by default.
Prioritizing Cleaning Operations
I've been thinking about the core data cleaning process and am now prioritizing certain common issues. Specifically, I'm focusing on whitespace, capitalization, duplicate rows, and problematic numeric strings. I'm refining the function's structure. It seems best to start with more general string cleanup, plus targeted numeric operations, and safe type inference. User control over date columns seems key. The user should be able to specify data types. I'm moving forward with a basic implementation draft.
Implementing Cleaning Operations
I'm now implementing the function's core cleaning operations. I've added whitespace trimming and duplicate removal, alongside NA value handling. I'm focusing on consistency in categorical data and parsing of numerical values including currency symbols. I'm exploring the best approach to date parsing. I am leaning toward a function approach over a class.
Finalizing Imputation Strategy
Now I'm focusing on missing values. For numeric columns, I'll use the mean for imputation. For object columns, I'll use the mode, or a placeholder like "Missing." The code structure is locked in. I'm focusing on making a dummy CSV in the explanation. It will show the script in action. I'm making sure to print what I've found.
Addressing Numeric Conversions
I'm now implementing the safeguard for numeric conversions. I want to avoid accidentally converting categorical IDs (like "00123") into integers ("123"). Therefore, I will either introduce a flag or adopt a conservative approach to numeric conversion. My focus will be on string columns with a mix of numbers and symbols.
Here is a robust, modular Python solution using the Pandas library. This solution is designed to handle the most common real-world CSV issues: whitespace, duplicates, inconsistent capitalization, currency symbols in numbers, and missing values.
The Solution
import pandas as pd
import numpy as np
import re
def clean_csv_data(input_file, output_file, date_cols=None, categorical_cols=None):
"""
Detects and corrects common inconsistencies in CSV data.
Args:
input_file (str): Path to the source CSV.
output_file (str): Path to save the cleaned CSV.
date_cols (list): List of column names to convert to datetime.
categorical_cols (list): List of column names to standardize (lowercase/strip).
"""
try:
# 1. Load Data
# include low_memory=False to ensure efficient type guessing for large files
df = pd.read_csv(input_file)
initial_rows = len(df)
print(f"--- Loaded '{input_file}' with {initial_rows} rows ---")
# 2. Standardize Column Names
# Remove spaces, make lowercase, replace special chars with underscore
df.columns = df.columns.str.strip().str.lower().str.replace(r'[^\w\s]', '', regex=True).str.replace(' ', '_')
print(f"✔ Standardized column names.")
# 3. Handle Duplicates
duplicate_count = df.duplicated().sum()
if duplicate_count > 0:
df = df.drop_duplicates()
print(f"✔ Removed {duplicate_count} duplicate rows.")
else:
print(f"✔ No exact duplicates found.")
# 4. String Hygiene (Whitespace & Formatting)
# Apply to all object (string) columns
for col in df.select_dtypes(include=['object']).columns:
# Strip leading/trailing whitespace
df[col] = df[col].str.strip()
# Fix "empty" strings being counted as valid data
df[col] = df[col].replace(r'^\s*$', np.nan, regex=True)
# Optional: Standardize specific categorical columns to lowercase
if categorical_cols:
clean_cat_cols = [c.lower().replace(' ', '_') for c in categorical_cols]
if col in clean_cat_cols:
df[col] = df[col].str.lower()
print(f"✔ Cleaned string whitespace and empty strings.")
# 5. Numeric Correction (Currency/Formatting cleaning)
# Detect columns that *should* be numbers but contain '$' or ','
for col in df.select_dtypes(include=['object']).columns:
# Check sample of non-null values to see if they look like numbers
sample = df[col].dropna().astype(str)
if sample.str.match(r'^[$\u20AC\u00A3]?[\d,.]+$').all():
print(f"ℹ Detected numeric data stored as text in '{col}'. Converting...")
# Remove currency symbols and commas
df[col] = df[col].replace(r'[$,]', '', regex=True)
df[col] = pd.to_numeric(df[col], errors='coerce')
# 6. Date Correction
if date_cols:
# Sanitize input list to match new snake_case column names
clean_date_cols = [c.lower().replace(' ', '_') for c in date_cols]
for col in clean_date_cols:
if col in df.columns:
df[col] = pd.to_datetime(df[col], errors='coerce')
print(f"✔ Converted '{col}' to datetime.")
# 7. Handle Missing Values (Imputation Strategy)
# Numeric: Fill with Median | Categorical: Fill with "Unknown"
# Numeric
num_cols = df.select_dtypes(include=['number']).columns
for col in num_cols:
if df[col].isnull().sum() > 0:
median_val = df[col].median()
df[col] = df[col].fillna(median_val)
print(f"✔ Filled missing values in numeric column '{col}' with median ({median_val}).")
# Categorical
cat_cols = df.select_dtypes(include=['object', 'category']).columns
for col in cat_cols:
if df[col].isnull().sum() > 0:
df[col] = df[col].fillna("Unknown")
print(f"✔ Filled missing values in text column '{col}' with 'Unknown'.")
# 8. Save Data
df.to_csv(output_file, index=False)
print(f"\n--- Success! Cleaned data saved to '{output_file}' ---")
print(f"Final shape: {df.shape}")
return df
except Exception as e:
print(f"❌ Error: {e}")
return None
# ==========================================
# Example Usage with Dummy Data Creation
# ==========================================
if __name__ == "__main__":
# 1. Create a dummy "messy" CSV file
import io
csv_content = """ID, Full Name , Join Date, Salary, Department
101, John Doe, 2023-01-15, "$60,000", IT
102, JANe Smith , 01/16/2023, $75000, HR
101, John Doe, 2023-01-15, "$60,000", IT
103, Bob Brown, ,$50,000,
104, , 2023-03-20, 80000, IT
105, Alice White, invalid_date, , Marketing
"""
# Save this content to a file for the function to read
with open("messy_data.csv", "w") as f:
f.write(csv_content)
# 2. Run the cleaner
clean_csv_data(
input_file="messy_data.csv",
output_file="clean_data.csv",
date_cols=["Join Date"],
categorical_cols=["Department", "Full Name"]
)
# 3. Display Result
print("\n--- Preview of Cleaned Data ---")
print(pd.read_csv("clean_data.csv"))
What this script does:
- Standardizes Headers: Converts
Full Name to full_name. It handles capitalization, stripping spaces, and removing special characters.
- Removes Duplicates: Checks the entire row for exact duplicates and removes them.
- Validates Text (Hygiene):
- Removes leading/trailing whitespace from values (e.g.,
" IT " becomes "IT").
- Converts empty strings (or strings with only spaces) into actual
NaN (null) objects so Pandas can detect them as missing.
- Standardizes casing for categorical columns (optional).
- Converting "Dirty" Numbers: Detects columns that look like currency (e.g.,
"$60,000") and converts them to actual floats/integers (60000.0) so you can do math on them.
- Fixes Dates: Converts specified columns to standard ISO format. If a date is completely unreadable (like "invalid_date"), it sets it to
NaT (Not a Time) rather than crashing.
- Smart Imputation (Filling Blanks):
- Numeric columns: Fills missing values with the Median (more robust against outliers than Mean).
- Text columns: Fills missing values with "Unknown" (safer than dropping data).
Code Requirements
You will need pandas installed:
pip install pandas