Monday, 26 July 2021

Pandas count number of rows since value > current cell

I have a Dataframe df:

       col_1
    0  51.0  
    1  52.0  
    2  51.5  
    3  51.5  
    4  53.0  
    5  54.0  
    6  52.0  
    7  53.0  
    8  50.5  
    9  50.0  
   10  52.0  

I would like to count the number of rows backwards until a value greater than the current value is found, or until the first row is reached. For example, the result would be:

       col_1 count
    0  51.0  0
    1  52.0  1
    2  51.5  0
    3  51.5  1
    4  53.0  4
    5  54.0  5
    6  52.0  0
    7  53.0  1
    8  50.5  0
    9  50.0  0
   10  52.0  2

I am basically trying to find the value of n in df['col_1'].rolling(n).max() for each value of the series. How can I do this? Thank you in advance.



from Pandas count number of rows since value > current cell

No comments:

Post a Comment