Just talking about how I solved a similar problem that I had. I did not want to accurately determine the index, I wanted to know how long ago the maximum value occurred. But it can also be used to search for an index.
I mainly use the shift strategy, but I repeat several shifts with a custom length. This is probably slow, but works well enough for me.
import pandas as pd length = 5 data = [1, 2, 3, 4, 5, 4, 3, 4, 5, 6, 7, 6, 5, 4, 5, 4, 3] df = pd.DataFrame(data, columns=['number']) df['helper_max'] = df.rolling(length).max() for i in range(length, -1, -1):
Output:
number helper_max n_rows_ago_since_max 0 1 NaN NaN 1 2 NaN NaN 2 3 NaN NaN 3 4 NaN NaN 4 5 5.0 0.0 5 4 5.0 1.0 6 3 5.0 2.0 7 4 5.0 3.0 8 5 5.0 0.0 9 6 6.0 0.0 10 7 7.0 0.0 11 6 7.0 1.0 12 5 7.0 2.0 13 4 7.0 3.0 14 5 7.0 4.0 15 4 6.0 4.0 16 3 5.0 2.0
source share