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

Python如何根据文件名日期提取指定年份最后一月CSV生成DataFrame

Python实现按年份最后一个月筛选合并CSV文件方案

完整实现代码

import os
import pandas as pd

# 配置参数
country = 'SouthKorea'
folder_path = f'../input/{country}'

# ------------可选:自动计算实际有文件的每年最后一个月前缀------------
# 提取所有csv文件的年月前缀,适配月份缺失场景
exist_ym = []
for file_name in os.listdir(folder_path):
    if file_name.endswith('.csv'):
        exist_ym.append(file_name[:6])
exist_ym = pd.to_datetime(pd.Series(exist_ym).unique(), format='%Y%m')
target_prefix = {
    '2020_last_month': exist_ym[exist_ym.year == 2020].max().strftime('%Y%m'),
    '2021_last_month': exist_ym[exist_ym.year == 2021].max().strftime('%Y%m')
}
# 如果确定要固定取2020年12月、2021年9月,直接替换上面的代码为:
# target_prefix = {
#     '2020_last_month': '202012',
#     '2021_last_month': '202109'
# }
# -------------------------------------------------------------------

# 初始化存储每个月分片DataFrame的列表
df_parts = {
    '2020_last_month': [],
    '2021_last_month': []
}

# 遍历所有文件筛选读取
for file_name in os.listdir(folder_path):
    # 跳过非csv文件
    if not file_name.endswith('.csv'):
        continue
    # 提取文件名前6位,对应%Y%m格式的年月
    file_ym = file_name[:6]
    # 匹配目标年月后读取
    if file_ym == target_prefix['2020_last_month']:
        tmp_df = pd.read_csv(os.path.join(folder_path, file_name))
        df_parts['2020_last_month'].append(tmp_df)
    elif file_ym == target_prefix['2021_last_month']:
        tmp_df = pd.read_csv(os.path.join(folder_path, file_name))
        df_parts['2021_last_month'].append(tmp_df)

# 合并得到最终结果,空数据场景兼容
df_2020_last = pd.concat(df_parts['2020_last_month'], ignore_index=True) if df_parts['2020_last_month'] else pd.DataFrame()
df_2021_last = pd.concat(df_parts['2021_last_month'], ignore_index=True) if df_parts['2021_last_month'] else pd.DataFrame()

方案说明

  • 效率优化:无需遍历日期范围,直接匹配文件名前6位的年月前缀,比逐天匹配速度提升数十倍
  • 兼容缺失场景:自动计算实际有文件的每年最后一个月,也支持手动固定目标年月
  • 异常兼容:自动跳过非CSV文件,对应月份无文件时返回空DataFrame不会报错
  • 扩展性强:需要新增其他年月统计时,仅需修改target_prefix字典即可

原有代码优化点

你原有代码是遍历每天的日期去匹配文件名,实际只要匹配前6位年月就能覆盖整月所有文件,不需要逐天循环,逻辑更简洁性能也更好。

内容的提问来源于stack exchange,提问作者nikki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:57:02