[Python] How to identify nth row that satisfies condition

Discussão em 'Python' iniciado por Stack, Junho 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dataframe with months and sales. If somebody does 250 sales for 3 consecutive months, they get a bonus.

    1. Once the bonus month is identified, the counter resets and starts to count the next 3 consecutive months with 250
    2. if there is less than 250 sales, then the counter resets
    Month sales 3 month consistency
    Month 1 250
    Month 2 250
    Month 3 250 1
    Month 4 250
    Month 5 250
    Month 6 250 1
    Month 7 0
    Month 8 250
    Month 9 250
    Month 10 250 1
    Month 11 250
    Month 12 250
    Month 13 0
    Month 14 250
    Month 15 250
    Month 16 250 1

    I want to populate the 3 month consistency column

    Tried using cum count with conditions but it did not work and I could not find such an example anywhere. What I tried was to use rolling window to identify every 3rd consecutive record with 250. But then it does not reset after the each set of 3 consecutive 250s.

    df.groupby('id').apply(lambda x: x['gt_250'].rolling(min_periods=1, window=3).sum())
    #-- grouped by id because this has to be computed for each salesperson_id


    The result I got from it was,

    Month sales 3 month consistency
    Month 1 250
    Month 2 250
    Month 3 250 3
    Month 4 250 3
    Month 5 250 3

    Continue reading...

Compartilhe esta Página