在 Pandas 中的接下来的 N 行中找到最大值的行偏移量?

Find the row offset for the maximum value over the next N rows in Pandas?

我在 Pandas DataFrame 中有一些数据:

  Price
1 
2 
3 
4 
5 
6 
7 

并且我正在尝试获取下一个 N 行最大值的 offset。例如,当 **** 时,输出看起来像

  Price  offset
1     2   <- offset is defined as the row offset of the maximum for the next two (N) values ( and )
2     2   <- similarly, the offset is here is the row offset of the maximum for the next two (N) values ( and )
3     1
4     1
5     2
6      1    
7     0

我可以使用以下 N 行获得最大值的

# Here, N=12
df['max_price'] = df['Price'].rolling(12).max().shift(-11)

但是,是否可以使用类似的逻辑来获取下N行最大值的行偏移位置任何指点会很有帮助。

你可以使用rolling,但你需要通过在反转系列上滚动来作弊。

s = df['Price'].str.strip('$').astype(int)

N = 2
df['offset'] = (s.iloc[::-1]
                .rolling(N, min_periods=1)
                .apply(lambda s: s.idxmax())
                .shift()
                .iloc[::-1]
                -df.index
                ).fillna(0, downcast='infer')

输出:

  Price  offset
1          2
2          2
3          1
4          1
5          2
6           1
7          0