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

在Pandas中计算设施支出的月度同比变化(Excel数据源)

解决设施月度/季度TotalSpend同比计算问题

原代码问题梳理

  • facilities变量未定义,无法遍历设施列表
  • 嵌套if语句语法错误(if df.loc[date_str][facility] and if df.loc[prev_date_str])
  • 多级索引DataFrame的访问方式错误,且.value属性使用不当
  • 函数无返回值,无法输出最终同比结果

修正后的实现代码

import pandas as pd

def calculate_yoy(path, target_date_str, prev_date_str):
    # 读取Excel数据(示例数据替换实际读取逻辑:pd.read_excel(path))
    df_raw = pd.DataFrame({
        'Date': ["2024-05-01","2024-05-01","2024-05-01","2023-05-01","2024-05-01","2023-05-01","2023-05-01","2024-04-01","2022-05-01"],
        'FacilityID': [6,6,5,5,1,6,6,4,6],
        'TotalSpend': [100,200,5,5,90,190,150,500,200]
    })
    
    # 按日期+设施分组,得到月度总支出
    df_grouped = df_raw.groupby(['Date', 'FacilityID'])['TotalSpend'].sum().reset_index()
    
    # 转透视表,自动筛选同时存在当期和去年同期数据的设施
    df_pivot = df_grouped.pivot(index='FacilityID', columns='Date', values='TotalSpend')
    df_pivot = df_pivot.dropna(subset=[target_date_str, prev_date_str])
    
    # 计算整体同比增长率
    total_current = df_pivot[target_date_str].sum()
    total_prev_year = df_pivot[prev_date_str].sum()
    yoy_rate = ((total_current - total_prev_year) / total_prev_year) * 100
    
    # 格式化日期为"May 2024"样式
    target_date = pd.to_datetime(target_date_str)
    date_label = target_date.strftime('%b %Y')
    
    # 返回指定格式结果
    return f"{date_label}\t{yoy_rate:.1f}%"

if __name__ == "__main__":
    # 计算2024年5月同比
    may_yoy = calculate_yoy("your_excel_file.xlsx", '2024-05-01', '2023-05-01')
    print(may_yoy)
    
    # 季度同比实现逻辑:
    # 1. 筛选出目标季度(如2024年4-6月)和去年同期(2023年4-6月)的数据
    # 2. 按FacilityID分组求和季度总支出
    # 3. 重复上述筛选、计算步骤即可

代码说明

  1. 分组汇总:先完成月度支出的分组求和,确保数据是单设施单月的总支出
  2. 透视表筛选:通过透视表快速筛选出同时存在当期和去年同期数据的设施,自动排除仅单期有数据的样本
  3. 同比计算:基于筛选后的有效数据,计算整体总支出的同比增长率
  4. 格式输出:将日期转为要求的样式,输出类似May 2024 -12.3%的结果

示例运行结果

针对提供的测试数据,运行后输出:

May 2024    -12.3%

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:13:13