如何计算滚动idxmax

piR*_*red 5 python numpy series dataframe pandas

考虑一下 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), list('abcdefghij'))
s

a    0
b    2
c    7
d    3
e    8
f    7
g    0
h    6
i    8
j    6
dtype: int64
Run Code Online (Sandbox Code Playgroud)

我想得到滚动窗口的最大值为3的索引

s.rolling(3).max()

a    NaN
b    NaN
c    7.0
d    7.0
e    8.0
f    8.0
g    8.0
h    7.0
i    8.0
j    8.0
dtype: float64
Run Code Online (Sandbox Code Playgroud)

我想要的是

a    None
b    None
c       c
d       c
e       e
f       e
g       e
h       f
i       i
j       i
dtype: object
Run Code Online (Sandbox Code Playgroud)

我做了什么

s.rolling(3).apply(np.argmax)

a    NaN
b    NaN
c    2.0
d    1.0
e    2.0
f    1.0
g    0.0
h    0.0
i    2.0
j    1.0
dtype: float64
Run Code Online (Sandbox Code Playgroud)

这显然不是我想要的

Bre*_*arn 10

没有简单的方法可以做到这一点,因为传递给滚动应用函数的参数是一个简单的numpy数组,而不是pandas Series,所以它不知道索引.此外,滚动函数必须返回浮点结果,因此如果它们不是浮点数,则它们不能直接返回索引值.

这是一种方法:

>>> s.index[s.rolling(3).apply(np.argmax)[2:].astype(int)+np.arange(len(s)-2)]
Index([u'c', u'c', u'e', u'e', u'e', u'f', u'i', u'i'], dtype='object')
Run Code Online (Sandbox Code Playgroud)

我们的想法是获取argmax值并将它们与系列对齐,方法是添加一个值,表示我们在系列中的距离.(也就是说,对于第一个argmax值,我们加零,因为它给我们索引到原始序列中从索引0开始的子序列;对于第二个argmax值,我们添加一个,因为它给了我们索引到一个从原始系列中的索引1开始的子序列;等等)

这给出了正确的结果,但在开头不包括两个"无"值; 如果你需要,你必须手动添加它们.

一个开放的熊猫问题来添加滚动idxmax.