Implementing CSV cleaning function
I'm implementing a Python function that reads a CSV, parses and flattens a nested JSON column into separate columns, and normalizes mixed-format dates to ISO 8601. It uses pandas, json, and pd.json_normalize to handle nested JSON, and pandas' to_datetime with dayfirst=True to parse dates consistently.
Below is a simple, self‑contained example that uses pandas and Python’s built‑in json module to:
- Load a CSV into a DataFrame
- Parse/flatten a column containing nested JSON into separate columns
- Normalize a date column that may contain mixed formats (
DD/MM/YYYY or YYYY-MM-DD) to ISO 8601 (YYYY-MM-DD)
import json
import pandas as pd
from pathlib import Path
from typing import Union
def clean_csv(
csv_path: Union[str, Path],
json_column: str,
date_column: str,
) -> pd.DataFrame:
"""
Load a CSV, flatten a JSON column into multiple columns, and normalize a
date column with mixed formats into ISO 8601 (YYYY-MM-DD).
Args:
csv_path (str | Path): Path to the CSV file.
json_column (str): Name of the column containing JSON strings.
date_column (str): Name of the column containing date strings.
Returns:
pd.DataFrame: Cleaned DataFrame with flattened JSON and normalized dates.
"""
# Read CSV
df = pd.read_csv(csv_path)
# --- Flatten JSON column ---
# Convert JSON strings to Python dicts (skip NaNs or invalid JSON)
json_series = df[json_column].apply(
lambda x: json.loads(x) if isinstance(x, str) else {}
)
# Flatten nested JSON to columns; use "." to separate nested keys
flattened = pd.json_normalize(json_series, sep=".")
# Add flattened columns to the DataFrame
df = df.drop(columns=[json_column]).reset_index(drop=True)
flattened = flattened.reindex(df.index) # align indexes
df = pd.concat([df, flattened], axis=1)
# --- Normalize date column ---
# mixed formats like "DD/MM/YYYY" and "YYYY-MM-DD"
# dayfirst=True helps parse dd/mm/..., errors='coerce' sets invalid dates to NaT
df[date_column] = pd.to_datetime(
df[date_column],
dayfirst=True,
errors="coerce",
infer_datetime_format=True,
).dt.strftime("%Y-%m-%d")
return df
# Example usage:
if __name__ == "__main__":
cleaned_df = clean_csv("input.csv", json_column="nested_json", date_column="date")
print(cleaned_df.head())
# Optionally save to a new CSV:
# cleaned_df.to_csv("cleaned_output.csv", index=False)
How it works
- Flatten JSON:
pd.json_normalize expands nested keys into separate columns. Nested fields become dot‑separated (e.g., "address.street").
- Normalize dates:
pd.to_datetime(..., dayfirst=True, infer_datetime_format=True) parses both DD/MM/YYYY and YYYY-MM-DD. The dt.strftime("%Y-%m-%d") step formats them to ISO 8601.
- You can adapt
sep="." to change how nested keys are separated in column names (e.g., "_").