如何计算滚动idxmax
考虑 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
我想获取滚动窗口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
我想要的是
a None
b None
c c
d c
e e
f e
g e
h f
i i
j i
dtype: object
我做了什么
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
这显然不是我想要的
-
没有简单的方法可以执行此操作,因为传递给rolling-applied函数的参数是一个普通的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')
这个想法是采用argmax值,并通过添加一个值来表示它们与序列对齐,该值指示我们在序列中的距离。(也就是说,对于第一个argmax值,我们加零,因为它给我们索引到原始序列中从索引0开始的子序列;对于第二个argmax值,我们加一个,因为它给我们索引到a从原始系列的索引1开始的子序列;依此类推)
这样可以得出正确的结果,但是开头不包括两个“ None”值。如果需要,您必须手动将其添加回去。
有一个开放的熊猫问题来添加滚动idxmax。