Ad

How To Get Number Of Rows Since Last Peak Pandas

- 1 answer

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
Ad

Answer

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()
                          )

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
Ad
source: stackoverflow.com
Ad