本文介紹了按 A 列刪除重復項,保留 B 列中值最高的行的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我在 A 列中有一個包含重復值的數據框.我想刪除重復項,將具有最高值的行保留在 B 列中.
I have a dataframe with repeat values in column A. I want to drop duplicates, keeping the row with the highest value in column B.
所以這個:
A B
1 10
1 20
2 30
2 40
3 10
應該變成這樣:
A B
1 20
2 40
3 10
我猜可能有一種簡單的方法可以做到這一點——可能就像在刪除重復項之前對 DataFrame 進行排序一樣簡單——但我不太了解 groupby 的內部邏輯,無法弄清楚.有什么建議嗎?
I'm guessing there's probably an easy way to do this—maybe as easy as sorting the DataFrame before dropping duplicates—but I don't know groupby's internal logic well enough to figure it out. Any suggestions?
推薦答案
這是最后一個.雖然不是最大值:
This takes the last. Not the maximum though:
In [10]: df.drop_duplicates(subset='A', keep="last")
Out[10]:
A B
1 1 20
3 2 40
4 3 10
你也可以這樣做:
In [12]: df.groupby('A', group_keys=False).apply(lambda x: x.loc[x.B.idxmax()])
Out[12]:
A B
A
1 1 20
2 2 40
3 3 10
這篇關于按 A 列刪除重復項,保留 B 列中值最高的行的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!