| import os |
| import re |
| import pandas as pd |
| from tqdm import tqdm |
| from datetime import datetime, timedelta |
|
|
| |
| def process_csv_files(input_dir, output_dir): |
| """ |
| 遍历指定目录下的所有.csv文件,并按要求处理数据。 |
| :param input_dir: 输入目录,包含原始.csv文件 |
| :param output_dir: 输出目录,保存处理后的.csv文件 |
| """ |
| |
| KEYWORDS = ["表面位移", "表面裂缝", "深部位移", "温度", "雨量"] |
| |
| for file_name in os.listdir(input_dir): |
| |
| if file_name.endswith(".csv"): |
| |
| A = file_name[:4] |
| print(f"Processing file: {file_name}, A = {A}") |
|
|
| |
| file_path = os.path.join(input_dir, file_name) |
| df = pd.read_csv(file_path) |
|
|
| |
| for keyword in KEYWORDS: |
| print(f"processing {keyword}") |
| |
| device_data_dict = {} |
| device_counter = 0 |
|
|
| |
| for index, row in tqdm(df.iterrows(), total=len(df), desc=f"file_name={file_name}, keyword={keyword}"): |
| |
| if re.search(keyword, row["设备名称"]): |
| |
| device_name = row["设备名称"] |
| data = row[["时间", "采集值x", "采集值y", "采集值z"]] |
|
|
| |
| if device_name not in device_data_dict: |
| device_data_dict[device_name] = {"data": [], "id": device_counter} |
| device_counter += 1 |
|
|
| |
| device_id = device_data_dict[device_name]["id"] |
|
|
| |
| device_data_dict[device_name]["data"].append(data) |
|
|
| |
| for device_name, info in device_data_dict.items(): |
| device_id = info["id"] |
| data_list = info["data"] |
|
|
| |
| device_df = pd.DataFrame(data_list, columns=["时间", "采集值x", "采集值y", "采集值z"]) |
|
|
| |
| keyword_output_dir = os.path.join(output_dir, keyword) |
| os.makedirs(keyword_output_dir, exist_ok=True) |
|
|
| |
| output_file_name = f"{keyword}_{device_id}_{A}.csv" |
| output_file_path = os.path.join(keyword_output_dir, output_file_name) |
| device_df.to_csv(output_file_path, index=False) |
| print(f"Saved file: {output_file_path}") |
|
|
|
|
| |
| def remove_duplicates(data_list): |
| seen = set() |
| result = [] |
| duplicate_count = 0 |
| for item in data_list: |
| if item not in seen: |
| seen.add(item) |
| result.append(item) |
| else: |
| duplicate_count += 1 |
| print(f"origin_len:{len(data_list)}") |
| print(f"after_duplication_len:{len(result)}") |
| print(f"Removed duplicates: {duplicate_count}") |
| return result, duplicate_count |
|
|
|
|
| |
| def smooth_data(data_list): |
| if not data_list or len(data_list) < 2: |
| return data_list, 0 |
|
|
| |
| def parse_timestamp_and_value(record): |
| parts = record.strip().split(',') |
| timestamp_str = parts[0] |
| values = [float(x) if x != 'NaN' and x != '' else 0.0 for x in parts[1:]] |
| timestamp = datetime.fromisoformat(timestamp_str.replace('+08', '+0800')) |
| return timestamp, values |
|
|
| |
| def format_record(timestamp, values): |
| timestamp_str = timestamp.strftime('%Y-%m-%d %H:%M:%S%z').replace('+0800', '+08') |
| values_str = ','.join(f"{v:.10f}" for v in values) |
| return f"{timestamp_str},{values_str}\n" |
|
|
| header = data_list[0] |
| data_list = data_list[1:] |
| result = [header] |
| supply_count = 0 |
| for i in tqdm(range(len(data_list) - 1), desc="Processing data", unit="step"): |
| current_timestamp, current_values = parse_timestamp_and_value(data_list[i]) |
| next_timestamp, next_values = parse_timestamp_and_value(data_list[i + 1]) |
| |
| if len(current_values) != len(next_values): |
| raise ValueError(f"数据行 {i} 和 {i+1} 的列数不一致") |
| result.append(format_record(current_timestamp, current_values)) |
| |
| time_diff = (next_timestamp - current_timestamp).total_seconds() / 60 |
| if time_diff > 10: |
| steps = int(time_diff / 10) |
| supply_count += steps - 1 |
| value_steps = [(next_values[j] - current_values[j]) / steps for j in range(len(current_values))] |
| for step in range(1, steps): |
| new_timestamp = current_timestamp + timedelta(minutes=step * 10) |
| new_values = [current_values[j] + step * value_steps[j] for j in range(len(current_values))] |
| result.append(format_record(new_timestamp, new_values)) |
| |
| last_timestamp, last_values = parse_timestamp_and_value(data_list[-1]) |
| result.append(format_record(last_timestamp, last_values)) |
| print(f"supply_num={supply_count}") |
| return result, supply_count |
|
|
|
|
| |
| def dep_and_smooth(input_file, output_file): |
| try: |
| |
| with open(input_file, 'r') as file: |
| data_list = file.readlines() |
| |
| print("Removing duplicates...") |
| data_list, duplicate_count = remove_duplicates(data_list) |
| |
| print("Smoothing data...") |
| data_list, supply_count = smooth_data(data_list) |
| |
| with open(output_file, 'w') as file: |
| file.writelines(data_list) |
| print(f"处理完成,结果已写入 {output_file}") |
| return duplicate_count, supply_count, len(data_list) |
| except Exception as e: |
| print(f"处理过程中发生错误:{e}") |
| return 0, 0, 0 |
|
|
|
|
| |
| def process_folder(input_folder, output_folder): |
| total_duplicate_count = 0 |
| total_supply_count = 0 |
| total_final_row_count = 0 |
|
|
| |
| if not os.path.exists(output_folder): |
| os.makedirs(output_folder) |
|
|
| |
| for root, dirs, files in os.walk(input_folder): |
| for file in files: |
| if file.endswith('.csv'): |
| |
| input_file_path = os.path.join(root, file) |
| |
| relative_path = os.path.relpath(root, input_folder) |
| output_subfolder = os.path.join(output_folder, relative_path) |
| if not os.path.exists(output_subfolder): |
| os.makedirs(output_subfolder) |
| output_file_path = os.path.join(output_subfolder, file) |
| |
| print(f"Processing file: {input_file_path}") |
| duplicate_count, supply_count, final_row_count = dep_and_smooth(input_file_path, output_file_path) |
| total_duplicate_count += duplicate_count |
| total_supply_count += supply_count |
| total_final_row_count += final_row_count |
|
|
| print(f"Total removed duplicates: {total_duplicate_count}") |
| print(f"Total added smooth data: {total_supply_count}") |
| print(f"Total final rows: {total_final_row_count}") |
|
|
|
|
| if __name__ == "__main__": |
| process_folder( |
| input_folder="/home/mby/time-series-transformer-demo/datasets/category_data", |
| output_folder="/home/mby/time-series-transformer-demo/datasets/category_data_processed" |
| ) |
|
|
| |
| |
| |
|
|