Pandas:滚动窗口获取第二大的值

3

我需要获取一个数据框(df)中第二大的滚动值。

要获取最大值,可以使用以下代码:

max = df.sort_index(ascending=True).rolling(10).max()

当我尝试这样做时,Python会抛出一个错误

max = df.sort_index(ascending=True).rolling(10).nlargest(2)

AttributeError: 'Rolling' object has no attribute 'nlargest'

这是一个错误吗?我还能使用什么性能更好的替代方法?


1
使用 max = df.sort_index(ascending=True).rolling(10).apply(lambda x: x[-2]) - Space Impact
这只有在值已经排序的情况下才有效,不是吗? - Itamar Mushkin
2个回答

6
我会像这样做:

我会采取类似的方法:

df.rolling(10).apply(lambda x: pd.Series(x).nlargest(2).iloc[-1])

3

使用np.sort按降序排序并选择第二个值:

np.random.seed(2019)

df = pd.DataFrame({
    'B': np.random.randint(20, size=15)
})
print (df)
     B
0    8
1   18
2    5
3   15
4   12
5   10
6   16
7   16
8    7
9    5
10  19
11  12
12  16
13  18
14   5

a = df.rolling(10).apply(lambda x: -np.sort(-x)[1]) 
#alternative
#a = df.rolling(10).apply(lambda x: np.sort(x)[-2]) 
print (a)
       B
0    NaN
1    NaN
2    NaN
3    NaN
4    NaN
5    NaN
6    NaN
7    NaN
8    NaN
9   16.0
10  18.0
11  16.0
12  16.0
13  18.0
14  18.0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接