[英]Group By Customer Id and Also Take Date Column With Most Recent Value In Pandas
我是使用 Python 和 Pandas 的新手,我有一個關於對我擁有的日期框進行分組的問題。
我按 id 對 dataframe 進行分組,但如果一個 id 有兩行,我只想取 category_timestamp 列中具有最新值的行。
這是 dataframe 中的結果:
id date_cancelled owner_id reason category_timestamp
610040 2020-06-23 15:26:32 345198 No Longer Qualifies 2020-06-23 15:26:15
122672 2020-06-23 15:30:35 28950 Billing Cancellation 2020-06-23 15:30:35
122672 2020-06-23 15:30:35 28950 No Contact 2018-04-26 8:45:17
862708 2020-06-23 17:31:03 327378 Changed Mind/Persuaded 2020-06-23 17:30:50
436932 2020-06-25 1:07:02 28950 No Contact 2019-08-09 8:02:05
所以我想要發生的是顯示兩次的id(122672),我只想顯示具有最新category_timestamp 的id。
如何將其添加到這行代碼中?
merged_df.groupby(['contact_id'])
謝謝!
我認為按日期對它們進行排序然后刪除重復項會更容易。
df = df.sort_values('date_cancelled', ascending=False)
df = df.drop_duplicates(subset='owner_id', keep='first')
print(df)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.