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

如何用Pandas计算年度实际变动?含通胀调整的月度对比需求

计算2023年月度A列相对2022年同月的实际变动

核心逻辑

要得到2023年各月A列相对2022年同月的实际变动,需分两步执行:

  • 先通过月度通胀计算累计通胀系数,将2022年同月的A值调整为2023年当月的等价购买力水平
  • 再用2023年当月A值与调整后的基准值对比,计算变动率

1. 累计通胀系数计算规则

以2022-04到2023-04为例:

  • 以2022-04为基数,初始累计通胀系数为1
  • 从2022-05到2023-04,每个月执行公式:累计通胀系数 = 上月系数 * (1 + 当月通胀值)
  • 最终2023-04的累计通胀系数为1.66(对应示例)

2. 实际变动率计算示例(2023-04)

  • 取2022-04的A值140,乘以累计通胀系数1.66,得到调整后基准值:140 * 1.66 = 232.2
  • 实际变动率公式:(2023-04的A值 - 调整后基准值) / 调整后基准值
  • 代入示例数据:(150 - 232.2) / 232.2 ≈ -0.35

Pandas 实现代码

假设你的DataFrame包含date(月度日期)、A(目标数值列)、inflation(月度通胀列),以下是完整实现:

import pandas as pd

# 示例DataFrame(替换为你的实际数据)
data = {
    'date': pd.date_range(start='2022-01', end='2023-04', freq='M'),
    'A': [120, 130, 135, 140, 142, 145, 148, 150, 152, 155, 158, 160, 162, 165, 150],
    'inflation': [0.02, 0.03, 0.025, 0.04, 0.035, 0.05, 0.045, 0.03, 0.025, 0.04, 0.035, 0.05, 0.04, 0.06]
}
df = pd.DataFrame(data)
df['date'] = df['date'].dt.to_period('M')  # 转为月度周期,简化同月匹配

# 拆分2022和2023年数据
df_2022 = df[df['date'].dt.year == 2022].set_index('date')
df_2023 = df[df['date'].dt.year == 2023].set_index('date')

# 定义函数:计算指定月份的累计通胀系数
def get_cumulative_inflation(month):
    start_period = pd.Period(f'2022-{month:02d}', freq='M')
    end_period = pd.Period(f'2023-{month:02d}', freq='M')
    # 获取周期内的通胀数据(跳过起始月的通胀,因为起始月系数为1)
    inflations = df.loc[df['date'].between(start_period, end_period), 'inflation'].iloc[1:]
    
    cum_inflation = 1.0
    for infl in inflations:
        cum_inflation *= (1 + infl)
    return cum_inflation

# 为2023年各月添加累计通胀系数
df_2023['cumulative_inflation'] = df_2023.index.month.map(get_cumulative_inflation)

# 匹配2022年同月的A值并计算调整后基准
df_2023['A_2022'] = df_2023.index.month.map(df_2022['A'])
df_2023['A_2022_adjusted'] = df_2023['A_2022'] * df_2023['cumulative_inflation']

# 计算实际变动率
df_2023['actual_change'] = (df_2023['A'] - df_2023['A_2022_adjusted']) / df_2023['A_2022_adjusted']

# 输出结果
print(df_2023[['A', 'A_2022', 'cumulative_inflation', 'A_2022_adjusted', 'actual_change']])

内容的提问来源于stack exchange,提问作者Fernando del Valle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 12:15:41