You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:10:30