import pandas as pd import os import sys def align_csv_structure(csv1_path, csv2_path): """ Reads csv1 and csv2, reformats csv1 to match csv2's columns, and overwrites csv1. """ # 1. 读取 CSV 文件 try: df1 = pd.read_csv(csv1_path) df2 = pd.read_csv(csv2_path) except FileNotFoundError as e: print(f"Error: {e}") return # 获取目标列结构 (来自 csv2) target_columns = df2.columns.tolist() # 2. 遍历目标列,处理 csv1 中缺失的列 for col in target_columns: if col in df1.columns: # 如果 csv1 已经有这个列,跳过(保留原数据) continue # 如果 csv1 缺少这个列,根据 pattern 进行生成或填充默认值 if col == 'id': # Pattern: 从 path 中提取文件名(不带扩展名) df1['id'] = df1['path'].apply(lambda x: os.path.splitext(os.path.basename(x))[0] if pd.notnull(x) else '') elif col == 'relpath': # Pattern: 从 path 中提取完整文件名 df1['relpath'] = df1['path'].apply(lambda x: os.path.basename(x) if pd.notnull(x) else '') elif col == 'audio_id': # Pattern: 从 audio_path 中提取文件名(不带扩展名) if 'audio_path' in df1.columns: df1['audio_id'] = df1['audio_path'].apply(lambda x: os.path.splitext(os.path.basename(x))[0] if pd.notnull(x) else '') else: df1['audio_id'] = '' elif col == 'audio_fps': # 默认填充 16000 (参考 csv2 的常见值,或者是 NaN) df1['audio_fps'] = 16000 # 处理 Category Title 列 (例如 cat0_title) elif 'title' in col and col.startswith('cat'): # 由于没有 ID 到 Title 的映射表,这里留空 df1[col] = '' # 其他技术参数 (num_frames, height, width, fps, aes, flow, ocr 等) else: # 填充为空值 (NaN),表示数据缺失 df1[col] = pd.NA # 3. 重新排序并筛选列,确保与 csv2 完全一致 # reindex 会自动丢弃 csv1 中多余的列(如果 csv2 没有的话),并对齐顺序 df1_final = df1.reindex(columns=target_columns) # 4. 覆盖保存 csv1 df1_final.to_csv(csv1_path, index=False) print(f"Successfully processed and overwritten: {csv1_path}") print(f"Columns aligned: {len(target_columns)}") if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: python align_csv.py ", file=sys.stderr) raise SystemExit(2) align_csv_structure(sys.argv[1], sys.argv[2])