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

Python pandas如何按日期范围筛选读取分月存储的Excel数据

enter image description here

实现方法

核心逻辑是先生成目标时间区间内所有符合命名规则的年月序列,匹配对应文件后批量读取合并,不需要手动遍历全量文件做过滤。

依赖导入

import pandas as pd
import os
from pandas import date_range

参数配置

根据实际文件存储情况修改对应值即可:

# 目标时间区间起止月份
start_month = "2020-01"
end_month = "2021-12"
# 月度Excel文件存放的文件夹路径
excel_folder = "./data"
# 文件后缀,旧版Excel改为.xls
file_ext = ".xlsx"

生成待读取文件列表

用pandas内置的日期序列方法自动处理跨年度、月份进位的边界问题,避免手动写循环判断的逻辑漏洞:

# 按月频生成区间内所有月份的第一天序列,格式化为和文件名一致的YYYY-MM字符串
target_months = date_range(start=start_month, end=end_month, freq="MS").strftime("%Y-%m").tolist()
# 拼接得到所有目标文件的完整路径
target_files = [os.path.join(excel_folder, f"{m}{file_ext}") for m in target_months]

批量读取合并

data_collector = []
for fp in target_files:
    # 存在性校验,避免个别月份文件缺失导致程序中断
    if not os.path.exists(fp):
        print(f"警告:文件{fp}不存在,已跳过")
        continue
    # 读取单月数据,可根据实际Excel结构加sheet_name、header等参数
    month_data = pd.read_excel(fp)
    # 可选:新增来源月份列,方便后续数据校验
    month_data["month_tag"] = os.path.basename(fp).replace(file_ext, "")
    data_collector.append(month_data)

# 合并为完整的区间数据集,重置索引
result_df = pd.concat(data_collector, ignore_index=True)

适配说明

  • 如果文件名带固定前缀,比如业务报表_2020-01.xlsx,只需要调整文件路径拼接部分的字符串格式,改为f"业务报表_{m}{file_ext}"即可。
  • 如果需要筛选Excel内的特定列,直接在read_excel里加usecols参数指定列名/列序号即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 16:48:45