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

如何在Polars中计算每行的累积和(cumsum)?

在Polars中计算DataFrame每行的累积和

你可以通过以下两种方式实现与Pandas cumsum(axis=1) 等效的行累积和计算:

方法1:使用row_cumsum方法

这是Polars专门用于行方向累积和的方法,兼容性较好:

import polars as pl
df = pl.DataFrame({'a': [1,2,3], 'b': [4,5,6]})

result = df.row_cumsum()
print(result)

方法2:使用cum_sum指定axis=1(Polars 0.19.0+)

如果你使用的是Polars 0.19.0或更高版本,可以直接通过axis参数指定行方向计算:

import polars as pl
df = pl.DataFrame({'a': [1,2,3], 'b': [4,5,6]})

result = df.cum_sum(axis=1)
print(result)

两种方法都会输出你预期的结果:

shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1   ┆ 5   │
│ 2   ┆ 7   │
│ 3   ┆ 9   │
└─────┴─────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:10:38