Pandas:滚动第二大值
Pandas: Rolling 2nd largest value
我需要获得 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'
这是一个错误吗?我还能使用什么是高性能的?
我会这样做:
df.rolling(10).apply(lambda x: pd.Series(x).nlargest(2).iloc[-1])
使用np.sort in descending order和select第二个值:
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
我需要获得 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'
这是一个错误吗?我还能使用什么是高性能的?
我会这样做:
df.rolling(10).apply(lambda x: pd.Series(x).nlargest(2).iloc[-1])
使用np.sort in descending order和select第二个值:
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