Python Dataframe根据列之一中的最大值选择行 [英] Python Dataframe select rows based on max values in one of the columns
本文介绍了Python Dataframe根据列之一中的最大值选择行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在python中有一个数据框(很多行,两列).我想根据第2列中的最大值用第1列中的唯一值修改DF(第2列按升序排序(如果有帮助的话)).我可能可以编写一个循环,但希望使用一两行的解决方案.谢谢.
I have a dataframe in python (many rows, 2 columns). I want to modify the DF with a unique value in column 1 based on the largest value in column 2 (column 2 is sorted in ascending order if that helps). I could probably write a loop but would prefer a one or two line solution. Thanks.
例如.
ID Value
100 11
100 14
100 16
200 10
200 20
200 30
300 45
400 0
400 25
期望的结果
100 16
200 30
300 45
400 25
推荐答案
您要 groupby
,然后使用
You want to groupby
on 'a' column and then get the index of the max value using idxmax
and use these indices to index the orig df:
In [12]:
df.loc[df.groupby('a')['b'].idxmax()]
Out[12]:
a b
2 100 16
5 200 30
6 300 45
8 400 25
这篇关于Python Dataframe根据列之一中的最大值选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文