如何合并CSV文件:按唯一Timestamp去重并前置新增有序数据?
合并CSV文件并实现去重、前置新增数据及有序排列的解决方案
方法一:使用Pandas(高效简洁)
适合处理较大数据集,代码量少易维护:
- 先确保已安装Pandas:
pip install pandas
- 执行以下代码:
import pandas as pd # 读取两个CSV文件 old_df = pd.read_csv('old.csv') new_df = pd.read_csv('new.csv') # 合并数据集并去重:保留原有(Old文件)的重复记录 combined_df = pd.concat([new_df, old_df]).drop_duplicates(subset='Timestamp', keep='last') # 将Timestamp转为时间格式并按降序排序(最新时间在前) combined_df['Timestamp'] = pd.to_datetime(combined_df['Timestamp']) combined_df = combined_df.sort_values(by='Timestamp', ascending=False) # 写入最终合并后的CSV combined_df.to_csv('merged.csv', index=False)
代码说明
pd.concat([new_df, old_df]):先将New文件数据放在前面,再拼接Old文件数据drop_duplicates(subset='Timestamp', keep='last'):按Timestamp去重,保留后面出现的Old文件记录(因为Old中Mined字段更贴近实际时间)- 转时间格式后降序排序,确保所有数据按时间从新到旧排列,自然实现新增数据前置且整体有序
方法二:纯Python实现(无需额外依赖)
适合无法安装第三方库的场景:
import csv from datetime import datetime # 读取Old文件,用字典存储以Timestamp为键的记录 old_records = {} with open('old.csv', 'r', newline='', encoding='utf-8') as old_file: reader = csv.DictReader(old_file) csv_header = reader.fieldnames for row in reader: old_records[row['Timestamp']] = row # 筛选New文件中未在Old里出现的记录 new_unique_records = [] with open('new.csv', 'r', newline='', encoding='utf-8') as new_file: reader = csv.DictReader(new_file) for row in reader: if row['Timestamp'] not in old_records: new_unique_records.append(row) # 合并新增记录与原有记录 all_records = new_unique_records + list(old_records.values()) # 按Timestamp降序排序(最新时间在前) all_records.sort( key=lambda x: datetime.strptime(x['Timestamp'], '%Y-%m-%d %H:%M:%S'), reverse=True ) # 写入合并后的CSV文件 with open('merged.csv', 'w', newline='', encoding='utf-8') as merged_file: writer = csv.DictWriter(merged_file, fieldnames=csv_header) writer.writeheader() writer.writerows(all_records)
代码说明
- 用字典存储Old文件记录,快速判断New文件中的记录是否重复
- 先收集New中的非重复记录,再拼接Old的全部记录
- 通过时间格式转换实现降序排序,保证整体数据按时间从新到旧排列
内容的提问来源于stack exchange,提问作者Gray Gillman
相关产品推荐
相关产品推荐

