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

如何按分组对每行计算滚动窗口内的idxmax?

解决Rolling对象无idxmax属性的问题

问题说明

  • 需求:按hy_code分组,获取每组最近6行数据中high列最大值对应的索引(week_date)
  • 报错代码:
df=df.assign(
        l6d_highest_date=lambda x: x.groupby('hy_code')['high'].transform(lambda x: x.rolling(6).idxmax())
)
  • 报错信息:AttributeError: 'Rolling' object has no attribute 'idxmax'
  • 注意:数据索引为week_date

解决方案

Pandas的Rolling对象没有内置idxmax方法,可通过rolling().apply()自定义函数实现需求,代码如下:

def get_rolling_idxmax(series):
    # 返回滚动窗口内最大值对应的索引
    return series.idxmax()

df = df.assign(
    l6d_highest_date=lambda x: x.groupby('hy_code')['high']
                                .transform(lambda s: s.rolling(6).apply(get_rolling_idxmax, raw=False))
)

关键细节

  • 设置raw=False,保证传入apply的是Series对象,才能调用idxmax()获取对应索引
  • 若数据存在缺失值,可添加min_periods参数(如rolling(6, min_periods=1)),避免窗口数据不足时返回NaN
  • 最终l6d_highest_date列会存储每组最近6行中high最大值对应的week_date索引

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:57:20