[英]How to remove duplicates based on two columns removing the the largest of 3rd column in pandas dataframe?
Suppose I have a pandas dataframe that is like this: 假设我有一个像这样的pandas数据框:
df=
A B 6 2
A C 4 2
D F 9 3
K L 8 9
A B 4 3
D F 8 2
How can I say, if columns A and B have duplicates remove the ones that have the largest column C? 我该怎么说,如果A列和B列重复,则删除C列最大的列?
So for instance we can see lines 1 and 5 have the same columns A and B. 因此,例如,我们可以看到第1行和第5行具有相同的A和B列。
A B 6 2 (Line 1)
A B 4 3 (Line 5)
I want to remove line 1 as 6 is greater than 4. 我想删除第1行,因为6大于4。
So my output should be 所以我的输出应该是
A C 4 2
K L 8 9
A B 4 3
D F 8 2
Try sorting the column in descending order on which you need to find max value using pd.sort_values
尝试按降序对列进行排序,您需要使用pd.sort_values
查找最大值
Then drop_duplicates using pd.drop_duplicate
然后使用pd.drop_duplicate
df.sort_values(by=['C'],ascending=[True],inplace=True)
df.drop_duplicates(subset=['A','B'],inplace=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.