Pandas select 根据绝对值从每组中选出前 2 名

Pandas select top 2 from each group based on absolute value

我有一个数据框 df:

Col1    Col2    Val1
A       a       -13
A       a       -101
A       a        40
A       b        22
B       b        3
B       b       -55
B       b        5
B       b       -27

我想获得以下信息:

Col1    Col2    Val1
A       a      -101
A       a       40
A       b       22
B       b      -55
B       b      -27

对于 Col1Col2 中的每个组,我根据 Val1 的绝对值选择前 2 名。我不确定如何处理这个问题。

我们可以做到:

df.loc[df['Val1'].abs().groupby([df['Col1'], df['Col2']])
                       .rank(ascending=False).le(2)]


  Col1 Col2  Val1
1    A    a  -101
2    A    a    40
3    A    b    22
5    B    b   -55
7    B    b   -27

另一个使用 argsort 的选项。

 df.loc[df['Val1'].abs().argsort()[::-1]].groupby(['Col1','Col2']).head(2).sort_values(by = 'Col1')