This is a comprehensive data cleaning task that requires:
- Reading CSV data
- Handling mixed date formats and converting to ISO 8601
- Parsing nested JSON in one column
- Flattening the JSON into new columns
- Returning clean data
Let me create a robust solution that handles edge cases and provides good documentation.
I'll need to:
- Use pandas for CSV handling
- Use json module for JSON parsing
- Use datetime for date parsing and formatting
- Handle errors gracefully
- Provide flexibility in choosing which columns contain JSON and dates
Here's my implementation plan:
- Create a function that takes CSV file path (or DataFrame)
- Accept parameters for which columns contain dates and JSON
- Parse and validate the JSON
- Flatten JSON keys
- Parse mixed date formats
- Normalize to ISO 8601
- Return cleaned DataFrame
Let me write this with comprehensive examples and error handling:
CSV Data Cleaning: JSON Flattening and Date Normalization
Here's a comprehensive solution to clean CSV data with nested JSON and mixed date formats:
import pandas as pd
import json
from datetime import datetime
from pathlib import Path
from typing import Union, Dict, List, Optional, Tuple
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class CSVDataCleaner:
"""Clean CSV data with nested JSON and mixed date formats."""
DATE_FORMATS = [
'%d/%m/%Y', # DD/MM/YYYY
'%Y-%m-%d', # ISO 8601
'%m/%d/%Y', # MM/DD/YYYY
'%d-%m-%Y', # DD-MM-YYYY
'%Y/%m/%d', # YYYY/MM/DD
'%d.%m.%Y', # DD.MM.YYYY
'%Y-%m-%d %H:%M:%S', # ISO with time
'%d/%m/%Y %H:%M:%S', # DD/MM/YYYY with time
]
def __init__(
self,
csv_file: Optional[Union[str, Path]] = None,
dataframe: Optional[pd.DataFrame] = None,
json_column: Optional[str] = None,
date_columns: Optional[List[str]] = None,
prefix_separator: str = '_',
):
"""
Initialize the cleaner.
Args:
csv_file: Path to CSV file
dataframe: Pandas DataFrame (alternative to csv_file)
json_column: Column name containing JSON data
date_columns: List of column names with mixed date formats
prefix_separator: Separator for flattened JSON keys
"""
self.prefix_separator = prefix_separator
self.json_column = json_column
self.date_columns = date_columns or []
if dataframe is not None:
self.df = dataframe.copy()
elif csv_file is not None:
self.df = pd.read_csv(csv_file)
else:
raise ValueError("Either csv_file or dataframe must be provided")
logger.info(f"Loaded data with shape: {self.df.shape}")
def parse_date(self, date_str: str) -> Optional[datetime]:
"""
Parse date string in mixed formats to datetime object.
Args:
date_str: Date string in various formats
Returns:
datetime object or None if parsing fails
"""
if pd.isna(date_str) or date_str == '':
return None
# Convert to string if not already
date_str = str(date_str).strip()
# Try each format
for fmt in self.DATE_FORMATS:
try:
return datetime.strptime(date_str, fmt)
except ValueError:
continue
# If no format matched, log warning
logger.warning(f"Could not parse date: '{date_str}'")
return None
def normalize_dates(self) -> 'CSVDataCleaner':
"""
Convert all date columns to ISO 8601 format (YYYY-MM-DD).
Returns:
self for method chaining
"""
for col in self.date_columns:
if col not in self.df.columns:
logger.warning(f"Column '{col}' not found in DataFrame")
continue
logger.info(f"Normalizing dates in column: {col}")
# Parse and convert to ISO format
self.df[col] = self.df[col].apply(
lambda x: self.parse_date(x).strftime('%Y-%m-%d')
if self.parse_date(x) else None
)
logger.info("Date normalization completed")
return self
def flatten_json_column(
self,
column: Optional[str] = None,
max_depth: int = 3,
) -> 'CSVDataCleaner':
"""
Flatten nested JSON in specified column into new columns.
Args:
column: Column name with JSON (uses self.json_column if None)
max_depth: Maximum depth to flatten
Returns:
self for method chaining
"""
column = column or self.json_column
if not column:
logger.warning("No JSON column specified")
return self
if column not in self.df.columns:
logger.warning(f"Column '{column}' not found")
return self
logger.info(f"Flattening JSON in column: {column}")
# Parse JSON and flatten
flattened_data = []
for idx, row in self.df.iterrows():
flat_dict = self._flatten_json_value(
row[column],
max_depth=max_depth
)
flattened_data.append(flat_dict)
# Create new DataFrame from flattened data
flattened_df = pd.DataFrame(flattened_data)
# Get all existing columns except the JSON column
non_json_cols = [col for col in self.df.columns if col != column]
# Combine original columns with flattened JSON
self.df = pd.concat(
[self.df[non_json_cols], flattened_df],
axis=1
)
# Drop original JSON column
self.df = self.df.drop(columns=[column])
logger.info(f"JSON flattening completed. New shape: {self.df.shape}")
return self
def _flatten_json_value(
self,
value: Union[str, Dict],
prefix: str = '',
max_depth: int = 3,
current_depth: int = 0,
) -> Dict:
"""
Recursively flatten JSON value.
Args:
value: JSON string or dictionary to flatten
prefix: Prefix for keys
max_depth: Maximum recursion depth
current_depth: Current recursion depth
Returns:
Flattened dictionary
"""
flat_dict = {}
# Parse JSON string if needed
if isinstance(value, str):
try:
value = json.loads(value)
except (json.JSONDecodeError, TypeError):
logger.debug(f"Could not parse JSON: {value}")
return {prefix or 'value': value}
if not isinstance(value, (dict, list)):
return {prefix or 'value': value}
# Stop if max depth reached
if current_depth >= max_depth:
return {prefix or 'value': value}
# Flatten dictionary
if isinstance(value, dict):
for key, val in value.items():
new_key = f"{prefix}{self.prefix_separator}{key}" if prefix else key
if isinstance(val, (dict, list)):
flat_dict.update(
self._flatten_json_value(
val,
prefix=new_key,
max_depth=max_depth,
current_depth=current_depth + 1,
)
)
else:
flat_dict[new_key] = val
# Flatten list
elif isinstance(value, list):
for i, item in enumerate(value):
new_key = f"{prefix}_{i}" if prefix else f"item_{i}"
if isinstance(item, (dict, list)):
flat_dict.update(
self._flatten_json_value(
item,
prefix=new_key,
max_depth=max_depth,
current_depth=current_depth + 1,
)
)
else:
flat_dict[new_key] = item
return flat_dict
def handle_missing_values(
self,
strategy: str = 'drop_rows',
fill_value: Optional[Union[str, int, float]] = None,
) -> 'CSVDataCleaner':
"""
Handle missing values.
Args:
strategy: 'drop_rows', 'drop_columns', or 'fill'
fill_value: Value to fill NaN (used with 'fill' strategy)
Returns:
self for method chaining
"""
if strategy == 'drop_rows':
initial_rows = len(self.df)
self.df = self.df.dropna()
logger.info(f"Dropped {initial_rows - len(self.df)} rows with missing values")
elif strategy == 'drop_columns':
cols_to_drop = self.df.columns[self.df.isna().all()].tolist()
self.df = self.df.drop(columns=cols_to_drop)
logger.info(f"Dropped columns with all NaN: {cols_to_drop}")
elif strategy == 'fill':
if fill_value is None:
fill_value = 'Unknown'
self.df = self.df.fillna(fill_value)
logger.info(f"Filled missing values with: {fill_value}")
return self
def remove_duplicates(self, subset: Optional[List[str]] = None) -> 'CSVDataCleaner':
"""
Remove duplicate rows.
Args:
subset: List of column names to consider for duplicates
Returns:
self for method chaining
"""
initial_rows = len(self.df)
self.df = self.df.drop_duplicates(subset=subset)
logger.info(f"Removed {initial_rows - len(self.df)} duplicate rows")
return self
def validate_cleaned_data(self) -> Dict[str, any]:
"""
Validate cleaned data quality.
Returns:
Dictionary with validation statistics
"""
stats = {
'total_rows': len(self.df),
'total_columns': len(self.df.columns),
'memory_usage_mb': self.df.memory_usage(deep=True).sum() / 1024**2,
'missing_values': self.df.isna().sum().to_dict(),
'duplicate_rows': self.df.duplicated().sum(),
'columns': list(self.df.columns),
}
logger.info(f"Validation stats: {stats}")
return stats
def get_cleaned_data(self) -> pd.DataFrame:
"""Get the cleaned DataFrame."""
return self.df.copy()
def save_to_csv(self, output_path: Union[str, Path]) -> None:
"""
Save cleaned data to CSV.
Args:
output_path: Path to output CSV file
"""
self.df.to_csv(output_path, index=False)
logger.info(f"Cleaned data saved to: {output_path}")
# ============================================================================
# EXAMPLE USAGE AND DEMONSTRATION
# ============================================================================
def create_sample_csv(file_path: str = 'sample_data.csv') -> None:
"""Create a sample CSV file with messy data."""
data = {
'id': [1, 2, 3, 4, 5],
'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
'join_date': ['01/01/2020', '2021-06-15', '15/03/2022', '2023-12-01', '25/12/2023'],
'update_date': ['2020-06-01', '15/07/2021', '2022-03-20', '01/12/2023', '2023-12-25'],
'metadata': [
'{"age": 30, "city": {"name": "NYC", "zip": "10001"}, "tags": ["python", "data"]}',
'{"age": 28, "city": {"name": "LA", "zip": "90001"}, "tags": ["java", "web"]}',
'{"age": 35, "city": {"name": "Chicago", "zip": "60601"}, "tags": ["ml"]}',
'{"age": 32, "city": {"name": "Houston", "zip": "77001"}, "tags": ["devops"]}',
'{"age": 27, "city": {"name": "Phoenix", "zip": "85001"}, "tags": ["frontend"]}',
],
}
df = pd.DataFrame(data)
df.to_csv(file_path, index=False)
logger.info(f"Sample CSV created: {file_path}")
return file_path
def example_basic_cleaning():
"""Example: Basic cleaning with all features."""
print("\n" + "="*70)
print("EXAMPLE 1: Basic Cleaning")
print("="*70)
# Create sample data
create_sample_csv('sample_data.csv')
# Initialize cleaner
cleaner = CSVDataCleaner(
csv_file='sample_data.csv',
json_column='metadata',
date_columns=['join_date', 'update_date'],
)
# Apply transformations
cleaner.normalize_dates().flatten_json_column().remove_duplicates()
# Validate and display
stats = cleaner.validate_cleaned_data()
print(f"\nCleaned data shape: {cleaner.get_cleaned_data().shape}")
print("\nFirst few rows:")
print(cleaner.get_cleaned_data().head())
# Save result
cleaner.save_to_csv('cleaned_data.csv')
return cleaner
def example_with_dataframe():
"""Example: Using DataFrame directly."""
print("\n" + "="*70)
print("EXAMPLE 2: Using DataFrame Directly")
print("="*70)
# Create data directly
data = {
'product_id': [101, 102, 103],
'created_date': ['10/01/2023', '2023-01-15', '20/01/2023'],
'properties': [
'{"brand": "Apple", "specs": {"cpu": "M1", "ram": 8}}',
'{"brand": "Dell", "specs": {"cpu": "i7", "ram": 16}}',
'{"brand": "HP", "specs": {"cpu": "Ryzen5", "ram": 8}}',
],
}
df = pd.DataFrame(data)
cleaner = CSVDataCleaner(
dataframe=df,
json_column='properties',
date_columns=['created_date'],
)
result = cleaner.normalize_dates().flatten_json_column().get_cleaned_data()
print("\nCleaned DataFrame:")
print(result)
return cleaner
def example_advanced_features():
"""Example: Advanced features and error handling."""
print("\n" + "="*70)
print("EXAMPLE 3: Advanced Features")
print("="*70)
# Create data with missing values
data = {
'id': [1, 2, 3, None, 5],
'date': ['01/01/2020', '2021-06-15', None, '2023-12-01', '25/12/2023'],
'config': [
'{"level": 1, "nested": {"value": 100}}',
'{"level": 2, "nested": {"value": 200}}',
'{"level": 1, "nested": {"value": 150}}',
'{"level": 3, "nested": {"value": 300}}',
'{"level": 2, "nested": {"value": 250}}',
],
'duplicate_check': ['a', 'b', 'a', 'c', 'd'],
}
df = pd.DataFrame(data)
cleaner = CSVDataCleaner(
dataframe=df,
json_column='config',
date_columns=['date'],
)
# Apply chain of operations
(cleaner
.normalize_dates()
.flatten_json_column(max_depth=2)
.remove_duplicates(subset=['duplicate_check'])
.handle_missing_values(strategy='fill', fill_value='N/A'))
result = cleaner.get_cleaned_data()
print("\nCleaned data with advanced options:")
print(result)
print("\nValidation statistics:")
stats = cleaner.validate_cleaned_data()
for key, value in stats.items():
if key != 'missing_values':
print(f" {key}: {value}")
return cleaner
def example_deep_nested_json():
"""Example: Deeply nested JSON structures."""
print("\n" + "="*70)
print("EXAMPLE 4: Deep Nested JSON")
print("="*70)
data = {
'id': [1, 2],
'timestamp': ['01/01/2020', '2021-06-15'],
'data': [
'{"user": {"profile": {"name": "Alice", "settings": {"theme": "dark", "notifications": true}}}}',
'{"user": {"profile": {"name": "Bob", "settings": {"theme": "light", "notifications": false}}}}',
],
}
df = pd.DataFrame(data)
cleaner = CSVDataCleaner(
dataframe=df,
json_column='data',
date_columns=['timestamp'],
prefix_separator='__'
)
result = (cleaner
.normalize_dates()
.flatten_json_column(max_depth=4)
.get_cleaned_data())
print("\nFlattened deeply nested JSON:")
print(result.to_string())
print(f"\nColumns created: {list(result.columns)}")
return cleaner
if __name__ == '__main__':
# Run all examples
example_basic_cleaning()
example_with_dataframe()
example_advanced_features()
example_deep_nested_json()
print("\n" + "="*70)
print("All examples completed successfully!")
print("="*70)
Key Features
1. Date Format Handling
- Supports multiple date formats (DD/MM/YYYY, YYYY-MM-DD, etc.)
- Graceful fallback with logging
- Converts to ISO 8601 format
2. JSON Flattening
- Recursive JSON parsing
- Configurable depth limit
- Custom key separator
- Handles nested lists and dictionaries
3. Method Chaining
cleaner.normalize_dates().flatten_json_column().remove_duplicates()
4. Error Handling
- Comprehensive logging
- Graceful degradation
- Detailed validation stats
Usage Examples
# Basic usage
cleaner = CSVDataCleaner(
csv_file='data.csv',
json_column='metadata',
date_columns=['created_at', 'updated_at']
)
cleaned_df = (cleaner
.normalize_dates()
.flatten_json_column()
.handle_missing_values(strategy='drop_rows')
.remove_duplicates()
.get_cleaned_data())
cleaner.save_to_csv('cleaned_data.csv')
This solution is production-ready with comprehensive logging, documentation, and error handling!