Pandas多索引DataFrame:在对1级索引进行分组时,保留列的N个最大条目 [英] Pandas multi index DataFrame: keep the N biggest entries of a column while grouping on level 1 index
本文介绍了Pandas多索引DataFrame:在对1级索引进行分组时,保留列的N个最大条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是具有多个索引行的示例DataFrame.
This is an example DataFrame with multi index rows.
row_idx_arr = list(zip(['r0', 'r0', 'r0', 'r1', 'r1', 'r1', 'r2', 'r2', 'r2', 'r3', 'r3', 'r3'], ['r-00', 'r-01', 'r-02', 'r-00', 'r-01', 'r-02', 'r-00', 'r-01', 'r-02', 'r-00', 'r-01', 'r-02', ]))
row_idx = pd.MultiIndex.from_tuples(row_idx_arr)
d = pd.DataFrame((np.random.randn(36)*10).reshape(12,3), index=row_idx, columns=['c0', 'c1', 'returns'])
c0 c1 returns
r0 r-00 3.553446 5.434018 5.141394
r-01 10.045250 18.453873 13.170396
r-02 -7.231743 -11.695715 5.303477
r1 r-00 -1.302917 6.461693 15.016544
r-01 13.348552 -9.133629 -2.464875
r-02 11.157144 16.833344 -8.745151
r2 r-00 -10.937900 -14.829996 -8.457521
r-01 -7.495922 9.269724 -5.001560
r-02 -8.966551 11.063291 -2.420552
r3 r-00 -21.434668 -0.730560 5.550830
r-01 16.590447 -0.432384 -0.396881
r-02 -0.636957 -2.765959 2.591906
我想创建一个新的DataFrame,其中对于每个1级索引值(r0,r1,r2,r3),我保留2个条目(2级行:r-00,r-01,r- 02)具有最高的回报率".
I'd like to create a new DataFrame where, for each level 1 index value (r0, r1, r2, r3), I keep the 2 entries (level 2 rows: r-00, r-01, r-02) with highest 'returns'.
请注意,这是一个示例,在我的程序中,我有数千行.
Please note that this is an example, in my program I have thousands of rows.
推荐答案
我认为您可以使用 查看全文