如何用大 pandas 删除除与某个值相对应的最大行以外的所有行? [英] How to remove all but the maximal row corresponding to some value with pandas?
本文介绍了如何用大 pandas 删除除与某个值相对应的最大行以外的所有行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表,其中有诸如
I have a table with rows such as
df = pandas.DataFrame([[2001, "Jack", 77], [2005, "Jack", 44], [2001, "Jill", 93]],columns=['Year','Name','Value'])
Year Name Value
0 2001 Jack 77
1 2005 Jack 44
2 2001 Jill 93
对于每个唯一的Name
,我想保留具有最大Year
值的行.在上面的示例中,我想要获取表
For each unique Name
, I would like to keep the row with the largest Year
value. In the above example I would like to get the table
Year Name Value
0 2005 Jack 44
1 2001 Jill 93
这可以通过简单的方式完成吗?
Can this be done in a simple way?
推荐答案
df.drop_duplicates(subset = 'Name', keep = 'last')
Year Name Value
1 2005 Jack 44
2 2001 Jill 93
像提到的@piRSquared一样编辑版本.
Writing an edited version just like @piRSquared mentioned.
df.sort_values('Year').drop_duplicates(subset = 'Name', keep = 'last')
这篇关于如何用大 pandas 删除除与某个值相对应的最大行以外的所有行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文