Skip to content Skip to sidebar Skip to footer

Pandas: Rolling 2nd Largest Value

I need to get the rolling 2nd largest value of a df. To get the largest value I do max = df.sort_index(ascending=True).rolling(10).max() When I try this, python throws an error m

Solution 1:

I'd do something like this:

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

Solution 2:

Use np.sort in descending order and select second value:

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
0NaN1NaN2NaN3NaN4NaN5NaN6NaN7NaN8NaN916.01018.01116.01216.01318.01418.0

Post a Comment for "Pandas: Rolling 2nd Largest Value"