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

在R语言中如何选取每月首个值并进行差值计算

解决方案:计算月度首值差值并匹配到对应行

原始数据

Date       Value
  1-Jun-12     5
  2-Jun-12     10
  3-Jun-12     8
  4-Jun-12     15
  2-Jul-12     12
  3-Jul-12     6 
  4-Jul-12     14
  1-Aug-12     20
  2-Aug-12     10

期望输出

Date       Value    mon_diff
  1-Jun-12     5           7 
  2-Jun-12     10
  3-Jun-12     8
  4-Jun-12     15          
  2-Jul-12     12          8
  3-Jul-12     6 
  4-Jul-12     14
  1-Aug-12     20          ...
  2-Aug-12     10

实现步骤(基于Pandas)

  1. 转换日期格式并生成分组标识
    先把Date列转为datetime类型,同时提取「年-月」作为分组键,避免不同年份的同月份混淆:

    import pandas as pd
    
    # 转换日期列格式
    df['Date'] = pd.to_datetime(df['Date'], format='%d-%b-%y')
    # 生成年月分组标识
    df['year_month'] = df['Date'].dt.to_period('M')
    
  2. 提取每个月的首值及对应行索引
    按「年-月」分组,获取每组的第一个Value值,以及该值所在行的索引:

    monthly_first = df.groupby('year_month').agg(
        first_value=('Value', 'first'),
        first_index=('Date', 'idxmin')
    ).reset_index()
    
  3. 计算月度首值差值
    使用shift方法获取下一个月的首值,计算「下月首值 - 当前月首值」的差值:

    monthly_first['mon_diff'] = monthly_first['first_value'].shift(-1) - monthly_first['first_value']
    
  4. 将差值填充回原始数据框
    初始化空的mon_diff列,把计算好的差值匹配到对应月份的首行,其余行留空:

    # 初始化mon_diff列
    df['mon_diff'] = ''
    # 填充对应行的差值
    for _, row in monthly_first.iterrows():
        df.loc[row['first_index'], 'mon_diff'] = row['mon_diff']
    # 删除临时分组列
    df.drop('year_month', axis=1, inplace=True)
    

补充处理

最后一个月没有下一个月的数据,mon_diff会是NaN,可以替换为需求中的...:

df['mon_diff'] = df['mon_diff'].fillna('...')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:50:29