熊猫:滚动第二大价值

时间:2019-06-12 05:34:16

标签: python pandas rolling-computation

我需要获得df的滚动第二最大值。

要获得最大的价值

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

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

当我尝试这样做时,python会引发错误

Shadow added on VStack creating problem. Pl check below code. I have comment shadow.

struct ContentView: View {

    @State var firstName = ""
    @State var lastName = ""
    var body: some View {

        NavigationView {

            VStack {

                VStack {

                    VStack {

                        Group {
                            TextField($firstName, placeholder: Text("First Name")).padding(10)
                            }.background(Color.black).clipShape(RoundedRectangle(cornerRadius: 5))
                            .shadow(radius: 3)

                        Group {
                            TextField($lastName, placeholder: Text("Last Name")).padding(10)
                            }.background(Color.black).clipShape(RoundedRectangle(cornerRadius: 5))
                            .shadow(radius: 3)

                        Button(action: {
                            print("Button Tapped")
                        }) {
                            Group {
                                Text("Create User").color(.white).padding(10)
                                }.background(Color.blue).clipShape(RoundedRectangle(cornerRadius: 5))
                                .shadow(radius: 5)
                        }
                        }.padding(12)
                        .background(Color.gray)
//                        .shadow(radius: 5)

                    }.background(Color.gray)

                }.navigationBarTitle(Text("Sign Up"))
        }
    }
}

这是一个错误吗?我还能用什么来表现呢?

2 个答案:

答案 0 :(得分:2)

我会做这样的事情:

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

答案 1 :(得分:2)

使用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