2 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個贊
我們可以嘗試GroupBy.head
new_df = df.sort_values('R').groupby('B', sort=False).head(3).head(5)
print(new_df)
? ? A? B? R
1? C2? A? 1
6? C7? B? 2
4? C5? B? 3
3? C4? B? 4
7? C8? C? 6

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個贊
top = df.merge(
df.groupby('B').R.nsmallest(3) # get the 3 top ranked rows for each group
.reset_index('B'),
# `nsmallest` will return a new df with B and df.index as MultiIndex
# so we reset B to a column
# however column A is not in this new df, so we merge with the original df
how='right') # and drop any rows not in the new df
輸出
A B R
0 C2 A 1
1 C3 A 7
2 C1 A 9
3 C7 B 2
4 C5 B 3
5 C4 B 4
6 C8 C 6
7 C9 C 8
8 C10 C 10
添加回答
舉報