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

如何使用Polars函数实现示例中的滚动最大值计算?

问题解答

你要实现的是累积最大值(从第一行到当前行所有值的最大值),Polars原生提供了cum_max()方法可以直接完成这个需求,无需使用窗口滚动或循环处理。

实现代码

import polars as pl

df1 = pl.DataFrame({"H": [3,2,1,4,6,5,9,8]})
df2 = df1.with_columns(rolling_highest=pl.col("H").cum_max())
print(df2)

输出结果

shape: (8, 2)
┌─────┬─────────────────┐
│ H   ┆ rolling_highest │
│ --- ┆ ---             │
│ i64 ┆ i64             │
╞═════╪═════════════════╡
│ 3   ┆ 3               │
│ 2   ┆ 3               │
│ 1   ┆ 3               │
│ 4   ┆ 4               │
│ 6   ┆ 6               │
│ 5   ┆ 6               │
│ 9   ┆ 9               │
│ 8   ┆ 9               │
└─────┴─────────────────┘

说明

cum_max()方法会逐行计算从数据集起始位置到当前行的最大值,完全匹配你需要的rolling_highest列逻辑,相比窗口滚动方法更高效——它不需要维护滑动窗口,而是直接追踪累积的最大值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 03:07:04