【问题标题】:Pandas: Rolling 2nd largest value熊猫:滚动第二大价值
【发布时间】:2019-10-26 13:23:18
【问题描述】:

我需要获取 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'

这是一个错误吗?我还能用什么性能好?

【问题讨论】:

  • 使用max = df.sort_index(ascending=True).rolling(10).apply(lambda x: x[-2])
  • 只有当值已经排序后才有效?

标签: python pandas rolling-computation


【解决方案1】:

使用np.sort in descending order 并选择第二个值:

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

【讨论】:

    【解决方案2】:

    我会这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-30
      • 2017-08-27
      • 1970-01-01
      • 2019-10-06
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      相关资源
      最近更新 更多