本文介绍了显示其他列时的分组列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据集,如下所示:
I have a dataset as follows:
name | $ | letter
adam, 34, c
beny, 45, e
adam, 55, a
beny, 87, t
我想提取每个名称所捐赠的最大金额以及相应的字母.所以对于亚当,我会得到:adam,55,a.
I'd like to extract the max $ donated by each name, with the respective letter.So for Adam, I would get: adam,55,a.
如果我使用:
df.groupby('name')[['$']].max()
那封信没有给我.
如果我使用:
df.groupby('name')[['$','letter']].max()
我得到了最大$和字母表中最高的字母.
I get the max $ and the highest letter in the alphabet.
推荐答案
使用 DataFrameGroupBy.idxmax
以获取最大值索引,然后通过 loc
:
print (df.groupby('name')['$'].idxmax())
name
adam 2
beny 3
Name: $, dtype: int64
df = df.loc[df.groupby('name')['$'].idxmax()]
print (df)
name $ letter
2 adam 55 a
3 beny 87 t
使用 sort_values
首先,然后使用 GroupBy.last
:
df = df.sort_values('$').groupby('name', as_index=False).last()
print (df)
name $ letter
0 adam 55 a
1 beny 87 t
解决方案中的差异是idxmax
设置原始索引,last
重置它们.
Difference in solutions is idxmax
let original indexes, last
reset them.
这篇关于显示其他列时的分组列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!