我在 Python Pandas 中有 DataFrame,如下所示:
date_col | ID | Phone
-----------|-----|--------
2020-05-17 | 111 | Apple
2020-06-11 | 111 | Sony
2021-12-28 | 222 | Sony
如您所見,ID“111”被重復,我需要在 ID 重復時這樣做,我需要從“date_col”列中獲取具有最新日期的行(此 col 格式為 datetime64)。因此,我需要類似下面的內容,因為 ID“111”重復但日期 2020-06-11 高于 2020-05-17:
date_col | ID | Phone
-----------|-----|--------
2020-06-11 | 111 | Sony
2021-12-28 | 222 | Sony
我怎樣才能在 Python Pandas 中做到這一點?
uj5u.com熱心網友回復:
嘗試:
df = df.sort_values(by="date_col").drop_duplicates(subset="ID", keep="last")
print(df)
印刷:
date_col ID Phone
1 2020-06-11 111 Sony
2 2021-12-28 222 Sony
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/484157.html
上一篇:拆分串列中的字串
