consider the pd.Series s
import pandas as pd
import numpy as np
np.random.seed([3,1415])
s = pd.Series(np.random.randint(0, 10, 10
Just chiming in on how I solved a similar problem that I had. I did not want to find the index exactly, I wanted to find how long ago the max value happened. But this could be used to find the index as well.
I'm basically using the shift strategy, but I'm iterating over several shifts with a configurable length. It's probably slow, but it works good 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):
# Set the column to what you want. You may grab the index
# if you wish, I wanted number of rows since max happened
df.loc[df['number'].shift(i) == df['helper_max'], 'n_rows_ago_since_max'] = i
print(df)
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