File size: 1,282 Bytes
8481f3c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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.") |