【问题标题】:Is it possible to "reset" cummax in Polars?是否可以在 Polars 中“重置”cummax?
【发布时间】:2023-02-10 00:14:36
【问题描述】:

当达到某个值时,我想重新开始累积最大值。例如。每次 cummax() 超过基础值 5% 时。我怎样才能在极地中做到这一点?

【问题讨论】:

  • 可重现的例子好吗?

标签: python-polars


【解决方案1】:

假设您想在值超过值 6 时重置 cummax。你可以这样做:

(
    df.with_columns(
        (pl.col("a") >= 6)
        .shift(1)
        .fill_null(False)
        .cumsum()
        .alias("group")
    ).with_columns(
        pl.col("a")
        .cummax()
        .over(pl.col("group"))
        .alias("cummax")
    )
)

例子:

In [73]: df = pl.DataFrame({'a': [1, 3, 5, 6, 1, 4, 3, 6, 5, 6]})

In [74]: (
    ...:     df.with_columns(
    ...:         (pl.col("a") >= 6)
    ...:         .shift(1)
    ...:         .fill_null(False)
    ...:         .cumsum()
    ...:         .alias("group")
    ...:     ).with_columns(
    ...:         pl.col("a")
    ...:         .cummax()
    ...:         .over(pl.col("group"))
    ...:         .alias("cummax")
    ...:     )
    ...: )
Out[74]:
shape: (10, 3)
┌─────┬───────┬────────┐
│ a   ┆ group ┆ cummax │
│ --- ┆ ---   ┆ ---    │
│ i64 ┆ u32   ┆ i64    │
╞═════╪═══════╪════════╡
│ 1   ┆ 0     ┆ 1      │
│ 3   ┆ 0     ┆ 3      │
│ 5   ┆ 0     ┆ 5      │
│ 6   ┆ 0     ┆ 6      │
│ ... ┆ ...   ┆ ...    │
│ 3   ┆ 1     ┆ 4      │
│ 6   ┆ 1     ┆ 6      │
│ 5   ┆ 2     ┆ 5      │
│ 6   ┆ 2     ┆ 6      │
└─────┴───────┴────────┘

【讨论】:

    猜你喜欢
    • 2022-08-04
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 2011-09-29
    • 2014-01-12
    • 1970-01-01
    相关资源
    最近更新 更多