[Python] Compute cumulative mean & std on polars dataframe (using over)

Discussão em 'Python' iniciado por Stack, Maio 14, 2025.

  1. Stack

    Stack Membro Participativo

    I want to compute the cumulative mean & std on a polars dataframe column.

    For the mean I tried this:

    import polars as pl

    df = pl.DataFrame({
    'value': [4, 6, 8, 11, 5, 6, 8, 15],
    'class': ['A', 'A', 'B', 'A', 'B', 'A', 'B', 'B']
    })

    df.with_columns(cum_mean=pl.col('value').cum_sum().over('class')
    / pl.int_range(pl.len()).add(1).over('class'))


    which correctly gives

    shape: (8, 3)
    ┌───────┬───────┬──────────┐
    │ value ┆ class ┆ cum_mean │
    │ --- ┆ --- ┆ --- │
    │ i64 ┆ str ┆ f64 │
    ╞═══════╪═══════╪══════════╡
    │ 4 ┆ A ┆ 4.0 │
    │ 6 ┆ A ┆ 5.0 │
    │ 8 ┆ B ┆ 8.0 │
    │ 11 ┆ A ┆ 7.0 │
    │ 5 ┆ B ┆ 6.5 │
    │ 6 ┆ A ┆ 6.75 │
    │ 8 ┆ B ┆ 7.0 │
    │ 15 ┆ B ┆ 9.0 │
    └───────┴───────┴──────────┘


    However, this seems very clunky, and becomes a little more complicated (and possibly error-prone) for std.

    Is there a nicer (possibly built-in) version for computing the cum mean & cum std?

    Continue reading...

Compartilhe esta Página