Search code examples
pythonpandasmaxminrolling-computation

Pandas: How to find the low after a high within a rolling window


For a series of numbers, I am trying to find the low after the high within a rolling window. I am able to calculate the high within the window, but not the low after it within the same window. I'm using Pandas and have tried to get the index of the high and use that as some type of reference, but I can't get it to work.

Here is some code to set up the problem:

 dates = pd.date_range("20130101", periods=15)
 temps = {'Temperature' :[16, 3, 26, 56, 2, 92, 54, 98, 73, 68, 80, 18, 75, 24, 12]}
 df = pd.DataFrame(temps, index=dates, columns = ['Temperature'])
 df['RollMax'] = df['Temperature'].rolling(5).max()
 # df['Low_After_High'] = ### Lowest value after high has been reached within the window

And here is what the output should look like:

enter image description here


Solution

  • Let us do apply with idxmax

    df['Low_After_High'] = df.Temperature.rolling(5).apply(lambda x : min(x[pd.Series(x).idxmax():]))
    2013-01-01     NaN
    2013-01-02     NaN
    2013-01-03     NaN
    2013-01-04     NaN
    2013-01-05     2.0
    2013-01-06    92.0
    2013-01-07    54.0
    2013-01-08    98.0
    2013-01-09    73.0
    2013-01-10    68.0
    2013-01-11    68.0
    2013-01-12    18.0
    2013-01-13    18.0
    2013-01-14    18.0
    2013-01-15    12.0
    Freq: D, Name: Temperature, dtype: float64