如何在R语言中为批量CSV文件添加对应日期列?
解决方案:为批量CSV文件添加对应日期列
核心思路
用Python的pandas库批量处理CSV文件,遍历文件列表和对应日期的配对,给每个文件新增一列并填充对应日期。
基础实现代码
import pandas as pd all_csvs = ['file1.csv', 'file2.csv'] dates = ['date1', 'date2'] # 配对遍历文件和日期 for csv_path, target_date in zip(all_csvs, dates): # 读取CSV到DataFrame df = pd.read_csv(csv_path) # 新增一列,整列填充目标日期 df['record_date'] = target_date # 列名可根据需求自定义 # 保存修改后的文件,index=False避免生成多余索引列 df.to_csv(csv_path, index=False) # 若不想覆盖原文件,可重命名保存: # df.to_csv(f"dated_{csv_path}", index=False)
注意事项
- 先确保安装了pandas:执行
pip install pandas - 如果处理超大CSV(内存无法一次性加载),用分块读取的方式避免内存溢出:
import pandas as pd all_csvs = ['file1.csv', 'file2.csv'] dates = ['date1', 'date2'] for csv_path, target_date in zip(all_csvs, dates): # 按10000行一块读取,可根据内存调整chunksize值 chunk_generator = pd.read_csv(csv_path, chunksize=10000) output_path = f"dated_{csv_path}" with open(output_path, 'w', newline='') as out_file: is_first_chunk = True for chunk in chunk_generator: chunk['record_date'] = target_date # 第一块保留表头,后续块不重复写入表头 chunk.to_csv(out_file, index=False, header=is_first_chunk) is_first_chunk = False
内容的提问来源于stack exchange,提问作者bblackburn
相关产品推荐
相关产品推荐

