我正在尝试将我的数据集分组为总体评价最高的年份。但是当我尝试使用 groupby nlargest 时,它仅返回年份并查看总体分数。
例如:
style | year | review_score
a | 1990 | 4.0
b | 1990 | 5.0
c | 1990 | 4.2
我的输出应该是
style | year | review_score
b | 1990 | 5.0
c | 1990 | 4.2
我尝试了以下方法:
v=style.groupby(by='review_year')['beer_style']['review_overall'].nlargest(3)
请帮助我
最佳答案
我认为需要set_index
需要保留在前面的所有列:
v = style.set_index('style').groupby(by='year')['review_score'].nlargest(2).reset_index()
print (v)
year style review_score
0 1990 b 5.0
1 1990 c 4.2
替代方案是首先按两列排序 sort_values
并调用GroupBy.head
:
v = (style.sort_values(['year','review_score'], ascending=(True, False))
.groupby(by='year').head(2))
print (v)
style year review_score
1 b 1990 5.0
2 c 1990 4.2
关于python - 将 pandas 中前 2 列最大值分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50169131/