import pandas as pd import os from tqdm import tqdm def clean_and_sort_csv(filepath, output_dir="cleaned_data"): """Clean CSV file and ensure chronological order""" os.makedirs(output_dir, exist_ok=True) df = pd.read_csv(filepath) # Ensure timestamp is datetime df['timestamp'] = pd.to_datetime(df['timestamp']) # Sort by timestamp df = df.sort_values('timestamp') # Remove duplicates df = df.drop_duplicates(subset=['timestamp']) # Forward fill any small gaps (optional) df = df.set_index('timestamp').asfreq('1H').ffill().reset_index() # Save cleaned file filename = os.path.basename(filepath) output_path = os.path.join(output_dir, filename) df.to_csv(output_path, index=False) return df def clean_all_data(input_dir="data", output_dir="cleaned_data"): """Process all CSV files in directory""" for root, _, files in os.walk(input_dir): for file in tqdm(files, desc="Cleaning files"): if file.endswith('.csv'): filepath = os.path.join(root, file) clean_and_sort_csv(filepath, output_dir) if __name__ == "__main__": clean_all_data() print("Data cleaning complete. Cleaned files saved to 'cleaned_data' folder.")