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

使用Pandas/Python基于多参数实现财务周对应报告周数的自动更新

Pandas自动化更新财务周报告表格方案

Pandas iterrows官方说明(中文翻译)

iterrows()返回的是每行数据的副本,修改返回值不会改动原DataFrame,且迭代操作性能远低于向量化批量操作,因此官方不建议使用iterrows()迭代修改DataFrame数据。

实现逻辑

完全使用Pandas向量化操作实现,不需要迭代DataFrame行,符合官方推荐的最佳实践,核心步骤如下:

  • 预处理:将表格中「财务周」列转为datetime格式,方便日期运算
  • 旧记录更新:直接过滤出Report Week < 13的所有行,批量将对应行的Report Week加1,同时更新财务周为当周的财务周起始日期
  • 过期记录清理:筛选出更新后Report Week = 13的记录,获取对应的月份列表,直接删除这些过期记录
  • 新记录新增:根据删除的月份,按公历顺序推下一个对应月份,新增对应行,设置财务周为当周日期,Report Week初始值为1

代码示例

import pandas as pd
from datetime import datetime, timedelta

# 1. 读取原有Excel表格
df = pd.read_excel("你的报告表格路径.xlsx")
# 转换财务周列为datetime格式
df["财务周(Finance Week)"] = pd.to_datetime(df["财务周(Finance Week)"])

# 2. 计算当前财务周(按规则为当周周一,可根据实际运行时间调整)
today = datetime.today()
current_finance_week = today - timedelta(days=today.weekday())

# 3. 批量更新未到13次的旧记录
update_mask = df["报告周(Report Week)"] < 13
df.loc[update_mask, "报告周(Report Week)"] += 1
df.loc[update_mask, "财务周(Finance Week)"] = current_finance_week

# 4. 清理已达13次的过期记录,记录要替换的月份
expire_mask = df["报告周(Report Week)"] == 13
expire_months = df.loc[expire_mask, "月份"].unique().tolist()
df = df[~expire_mask]

# 5. 新增下一个月份的记录
# 月份映射,方便计算下一个月
month_map = {"一月":2, "二月":3, "三月":4, "四月":5, "五月":6, "六月":7,
             "七月":8, "八月":9, "九月":10, "十月":11, "十一月":12, "十二月":1}
reverse_month_map = {v:k for k,v in month_map.items()}

for m in expire_months:
    next_month_num = month_map[m]
    next_month_name = reverse_month_map[next_month_num]
    # 新增行
    new_row = pd.DataFrame([{
        "月份": next_month_name,
        "财务周(Finance Week)": current_finance_week,
        "报告周(Report Week)": 1
    }])
    df = pd.concat([df, new_row], ignore_index=True)

# 6. 保存回Excel
df.to_excel("你的报告表格路径.xlsx", index=False)

注意事项

  • 首次运行前请备份原有Excel文件,避免数据误改
  • 如果财务周的起始规则不是自然周周一,可以调整current_finance_week的计算逻辑
  • 季度规则如果有特殊调整,可修改月份映射的对应逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:00:00