[Python] Polars Rolling_mean negative values

Discussão em 'Python' iniciado por Stack, Agosto 26, 2025.

  1. Stack

    Stack Membro Participativo

    Daily variation analysis in Polars: Rolling std for negative values only

    The situation


    Hi there, I have a Polars DataFrame with columns like ['Date','category','number'], already grouped. This DataFrame contains almost all dates for 7 months (close to 25 million rows).

    I want to perform some analysis about the growth for each category. A simple way to start is by identifying days with significant positive or negative daily variations.

    What I want to calculate

    • daily_variation
    • %daily_variation
    • rolling_mean_%daily_variation_30_days
    • rolling_mean_%daily_std_30_days
    • rolling_mean_%daily_std_30_days_neg_values ← This is where I'm stuck
    The problem


    I realize that Polars doesn't have a straightforward method for calculating a rolling std of only negative values (or I lack the knowledge). I've tried various approaches but can't figure out how to filter only negative values within a rolling window operation.

    How can I calculate a rolling std that only considers negative values within each 30-day window?

    Any help would be greatly appreciated!

    What I've tried


    # This works fine for regular rolling mean
    df = df.with_columns([
    pl.col("daily_variation_pct").rolling_stdwindow_size=30).alias("rolling_std_30d")
    ])

    # But I need something like this for negative values only:
    # df.with_columns([
    # pl.col("daily_variation_pct").filter(< 0).rolling_std(30).alias("rolling_std_30d_neg")
    # ])

    Continue reading...

Compartilhe esta Página