我有一个数据框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
对于Col1
和Col2
中的每个组,我根据Val1
的绝对值选择前2名。我不确定该如何处理。
答案 0 :(得分:4)
我们可以做到:
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
答案 1 :(得分:0)
另一个使用argsort的选项。
df.loc[df['Val1'].abs().argsort()[::-1]].groupby(['Col1','Col2']).head(2).sort_values(by = 'Col1')