2 回答
TA贡献1780条经验 获得超3个赞
我们可以尝试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贡献1824条经验 获得超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
添加回答
举报