Home > Mobile >  How to get number of rows since last peak Pandas
How to get number of rows since last peak Pandas

Time:08-11

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

CodePudding user response:

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
  • Related