Designing Python function for CSV cleaning
The user wants me to implement a Python function to detect and correct common data inconsistencies in CSV files. It's unclear what specific inconsistencies they mean, but I’m thinking of issues like missing values, whitespace, casing, and duplicates. I should create a function that takes a CSV path and optionally a schema definition, which returns a cleaned DataFrame or writes to a new CSV. Using pandas seems like the best route for clarity and efficiency. I'd like to incorporate logging of the corrections made.Implementing the CSV cleaning function
It looks like the user just wants me to implement a Python function, so I'm thinking of creating clean_csv with several parameters like infile, outfile, encoding, and options for handling datetime and numeric columns. I’ll define a list of null-like values and use na_values when reading the CSV. I want to address common inconsistencies, including fixing whitespace, unifying casing, normalizing missing data, and parsing mixed date formats. Also, I need a function to handle numbers stored as strings with thousands separators. That should cover a lot!Addressing data inconsistencies in CSVs
I’m considering the danger of decimal mark confusion, but I can implement a robust solution. I might use the locale or regex to handle values, but I want a simpler approach to remove thousands separators while parsing. For boolean values, I'll map common strings, like {"yes", "no"} to their respective truth values. I'll also drop duplicate and empty rows. Quoting issues can be automatically managed by pandas, and I prefer using pandas for these operations, starting with reading the CSV as a string.Implementing detection heuristics
I’m planning to implement detection heuristics for different data types. For dates, I can create a function that checks if a series likely contains dates by parsing them and checking if most are valid. For numeric values, I’ll clean the string by removing certain characters and converting it to numeric types. I also need to define TRUE and FALSE values for booleans. Plus, for categorical normalization, I’ll convert low cardinality object columns into categories after cleaning. I want to keep my explanations clear and brief, while mentioning that if pandas isn’t preferred, the csv module could be an alternative.Crafting the CSV cleaning function
I need to provide a complete script that the user can easily copy-paste. I'll create a clean_csv function with optional parameters for schema mapping and perform common data cleaning tasks, including reading the CSV and defining a list of null-like values. I plan to handle whitespace, drop empty rows, and unify types for boolean, numeric, and categorical data. Standardizing column names is also an option. I should ensure that the docstring is informative but concise, with an example at the bottom for clarity. Time to put it all together!Designing the CSV cleaning function
I'm planning to create a robust clean_csv function that implements clear steps for cleaning data. The function will read a CSV file, standardize column names, strip unnecessary whitespace, and handle null-like values. I need to include detection functions for boolean, numeric, and date types to ensure accurate data conversions. However, I'll rely on user input for numeric and date columns to avoid pitfalls in automatic detection. My aim is to keep the code modular while implementing safe heuristics for effective data cleaning. Let’s get this structured properly!Implementing column inference and casting
I’m working on the infer_and_cast_column function, which will handle data type detection and conversions. It will check if non-null values fall into boolean, date, or numeric categories. For numeric detection, I’ll need to carefully manage decimal and thousands separators to avoid erroneous conversions. I also want to incorporate _looks_like_date to check for date-like patterns properly. Plus, I need to ensure I'm replacing null-like values consistently. Finally, I’ll provide a usage example to show how this cleaning process works. Let's get everything organized! Below is a reusable, self‑contained implementation using pandas that detects and corrects several common inconsistencies in CSV files:
- Trim leading/trailing whitespace in column names and cell values
- Standardize “null-like” values to proper missing values (
NaN)
- Drop completely empty rows
- Infer and fix column types:
- Booleans like
yes/no, true/false, 0/1
- Dates in common formats
- Numeric columns with thousands separators (US style:
1,234.56)
- Optionally standardize column names and drop duplicate rows
import re
from typing import Optional
import numpy as np
import pandas as pd
# Common null-like markers seen in CSVs
NULL_LIKE = [
"", " ", "-", "--",
"NA", "N/A", "na", "n/a",
"NULL", "null",
"None", "none",
]
# Common boolean string values
TRUE_VALUES = {"true", "t", "yes", "y", "1"}
FALSE_VALUES = {"false", "f", "no", "n", "0"}
def _looks_like_date(non_null: pd.Series) -> bool:
"""
Heuristic: values that mostly contain date separators and
are successfully parsed by pandas.
"""
if non_null.empty:
return False
# Must have at least some typical date separators in the majority of values
has_sep_ratio = non_null.str.contains(r"[-/\.]", regex=True).mean()
if has_sep_ratio < 0.5:
return False
parsed = pd.to_datetime(
non_null,
errors="coerce",
infer_datetime_format=True,
dayfirst=False,
)
return parsed.notna().mean() > 0.9
def _looks_like_numeric(non_null: pd.Series) -> bool:
"""
Heuristic: values that look like standard US-style numbers:
optional sign, digits, optional decimal point, optional thousands
separators (commas).
"""
if non_null.empty:
return False
# Allow digits, commas, decimal point, spaces, sign
cleaned = non_null.str.replace(r"[,\s]", "", regex=True)
mask = cleaned.str.fullmatch(r"[+-]?(\d+(\.\d*)?|\.\d+)")
return mask.mean() > 0.9
def _infer_and_cast_column(s: pd.Series) -> pd.Series:
"""
Infer column type from string data and cast accordingly.
Assumes `s` is of dtype object/string with NaNs.
"""
non_null = s.dropna()
if non_null.empty:
return s
# 1. Boolean detection (yes/no, true/false, 0/1)
lower = non_null.str.lower()
unique_vals = set(lower.unique())
bool_keys = TRUE_VALUES | FALSE_VALUES
if unique_vals.issubset(bool_keys):
mapping = {**{k: True for k in TRUE_VALUES},
**{k: False for k in FALSE_VALUES}}
return s.str.lower().map(mapping).astype("boolean")
# 2. Date detection
if _looks_like_date(non_null):
return pd.to_datetime(
s,
errors="coerce",
infer_datetime_format=True,
)
# 3. Numeric detection (US-style: 1,234.56)
if _looks_like_numeric(non_null):
cleaned = s.str.replace(r"[,\s]", "", regex=True)
return pd.to_numeric(cleaned, errors="coerce")
# 4. Otherwise: leave as text; compress to category if low cardinality
nunique = non_null.nunique()
if nunique < 50 and nunique / len(non_null) < 0.5:
return s.astype("category")
return s
def clean_csv(
input_path: str,
output_path: Optional[str] = None,
*,
encoding: str = "utf-8",
standardize_column_names: bool = True,
drop_duplicate_rows: bool = True,
) -> pd.DataFrame:
"""
Load a CSV, detect & correct common inconsistencies, and optionally
write a cleaned CSV.
Fixes:
- Trims whitespace from column names and cell values
- Standardizes null-like markers to NaN
- Drops completely empty rows
- Infers booleans, dates, and numeric columns (US-style numbers)
- Optionally standardizes column names (lowercase, underscores)
- Optionally drops duplicate rows
Parameters
----------
input_path : str
Path to the raw CSV file.
output_path : str, optional
If provided, write the cleaned CSV here.
encoding : str, default 'utf-8'
File encoding.
standardize_column_names : bool, default True
If True: strip, lowercase, and replace non-word chars with '_'.
drop_duplicate_rows : bool, default True
If True: drop completely duplicate rows.
Returns
-------
pandas.DataFrame
Cleaned DataFrame.
"""
# Read everything as string initially so we can clean consistently
df = pd.read_csv(
input_path,
dtype=str,
encoding=encoding,
na_values=NULL_LIKE + ["#N/A", "#VALUE!"],
keep_default_na=True,
skip_blank_lines=True,
)
# Clean column names
if standardize_column_names:
df.columns = [
re.sub(r"\W+", "_", col.strip().lower())
for col in df.columns
]
else:
df.columns = [col.strip() for col in df.columns]
# Drop rows that are completely empty
df = df.dropna(how="all")
# Strip whitespace from all string cells
for col in df.columns:
# At this stage all columns are object dtype
df[col] = df[col].str.strip()
# Standardize null-like values (after stripping)
df.replace({v: np.nan for v in NULL_LIKE}, inplace=True)
df.replace(r"^\s*$", np.nan, regex=True, inplace=True)
# Infer and cast column types
for col in df.columns:
df[col] = _infer_and_cast_column(df[col])
# Drop duplicate rows if requested
if drop_duplicate_rows:
df = df.drop_duplicates()
# Optionally write to disk
if output_path is not None:
df.to_csv(output_path, index=False, encoding=encoding)
return df
if __name__ == "__main__":
# Example usage
cleaned = clean_csv("raw_data.csv", "cleaned_data.csv")
print(cleaned.dtypes)
print(cleaned.head())
Notes / how to adapt:
- If your numbers use a different style (e.g.,
1.234,56), adjust _looks_like_numeric and the cleaning rule inside it.
- If you know specific columns should be dates or numerics, you can skip guessing and force those conversions directly (e.g.,
df["my_date"] = pd.to_datetime(df["my_date"], errors="coerce")) before or after calling _infer_and_cast_column.
- You can extend
NULL_LIKE, TRUE_VALUES, and FALSE_VALUES to match your data conventions.