How to get number of rows since last peak Pandas

Viewed 24

I would like to get a rolling count of how many rows have been between the current row and the last peak. Example code:

Value | Rows since Peak
-----------------------
   1       0
   3       0
   1       1
   2       2
   1       3
   4       0
   6       0
   5       1
1 Answers

You can compare the values to the cummax and use it for a groupby.cumcount:

df['Rows since Peak'] = (df.groupby(df['Value'].eq(df['Value'].cummax())
                                    .cumsum())
                           .cumcount()
                          )

How it works:

Every time a value is equal to the cumulated max (df['Value'].eq(df['Value'].cummax())) we start a new group (using cumsum to define the group). Then cumcount enumerates since the start of the group.

output:

   Value  Rows since Peak
0      1                0
1      3                0
2      1                1
3      2                2
4      1                3
5      4                0
6      6                0
7      5                1
Related