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

Polars转Pandas逻辑报错:Series无cumsum属性,如何实现相同输出?

Pandas转Polars:非空连续段分组计算的问题修复

问题背景

有一段Pandas代码,实现对reserved_before字段的非空连续段分组,计算每组的最小、最大值。转换为Polars代码时,触发以下错误:

AttributeError: 'Series' object has no attribute 'cumsum'

报错原因

Polars的Series对象没有cumsum()方法,必须使用Polars的表达式语法(pl.col())调用累加函数。Pandas中布尔值的cumsum()会自动将True转为1、False转为0进行累加,Polars需要显式完成布尔值到数值的转换。

修复后的Polars代码

将分组ID生成逻辑替换为Polars表达式语法,完整代码如下:

import polars as pl
from datetime import date

df = pl.DataFrame({
    'date': pl.date_range(start=date(2024, 9, 1), end=date(2024, 9, 12), interval='1d', eager=True),
    'reserved_before': [0, 1, 2, None, None, 1, 2, 3, None, 3, 4, 5]
})

df = df.with_columns(
    pl.col('reserved_before').is_not_null().alias('reserved')
)

# 核心修复:用Polars表达式实现分组ID生成,与Pandas逻辑完全对齐
df = df.with_columns(
    (pl.col('reserved') != pl.col('reserved').shift(1)).cast(pl.Int32).cumsum().alias('group')
)

min_max_df = (
    df.groupby('group')
    .agg(
        pl.col('reserved_before').min().alias('block_min'),
        pl.col('reserved_before').max().alias('block_max')
    )
)

df = df.join(min_max_df, on='group', how='left').drop('group', 'reserved')
print(df)

验证结果

运行后输出与Pandas代码完全一致:

┌────────────┬────────────────┬──────────┬──────────┐
│ date       ┆ reserved_before┆ block_min┆ block_max│
│ ---        ┆ ---            ┆ ---      ┆ ---      │
│ date       ┆ i64            ┆ i64      ┆ i64      │
╞════════════╪════════════════╪══════════╪══════════╡
│ 2024-09-01 ┆ 0              ┆ 0        ┆ 2        │
│ 2024-09-02 ┆ 1              ┆ 0        ┆ 2        │
│ 2024-09-03 ┆ 2              ┆ 0        ┆ 2        │
│ 2024-09-04 ┆ null           ┆ null     ┆ null     │
│ 2024-09-05 ┆ null           ┆ null     ┆ null     │
│ 2024-09-06 ┆ 1              ┆ 1        ┆ 3        │
│ 2024-09-07 ┆ 2              ┆ 1        ┆ 3        │
│ 2024-09-08 ┆ 3              ┆ 1        ┆ 3        │
│ 2024-09-09 ┆ null           ┆ null     ┆ null     │
│ 2024-09-10 ┆ 3              ┆ 3        ┆ 5        │
│ 2024-09-11 ┆ 4              ┆ 3        ┆ 5        │
│ 2024-09-12 ┆ 5              ┆ 3        ┆ 5        │
└────────────┴────────────────┴──────────┴──────────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 17:20:11