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

Polars中是否有等价于pandas groupby().shift()的实现方法?

Polars中实现类似pandas groupby().shift()的方法

Polars完全支持分组内的shift操作,有两种常用实现方式,效果和pandas的df.groupby().shift()完全等价:

  • 使用groupby后直接调用shift方法
    先构造示例数据:

    import polars as pl
    
    df = pl.DataFrame({
        "group": ["A", "A", "B", "B", "B"],
        "value": [1, 2, 3, 4, 5]
    })
    

    执行分组shift:

    # 每个组内向下shift 1位
    grouped_shift_result = df.groupby("group").shift(1)
    

    结果中每个分组的第一行会出现null,后续行对应组内上一行的value,和pandas的分组shift逻辑一致。

  • 使用窗口函数over实现(更灵活,可保留原数据)
    如果需要在原DataFrame中新增shift后的列,可直接用窗口函数:

    result_with_shifted_col = df.with_columns(
        pl.col("value").shift(1).over("group").alias("shifted_value")
    )
    

    这种方式不会改变原有数据结构,直接添加分组shift后的结果列,适合需要同时查看原数据和shift结果的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:27:25