【问题标题】:Group By Customer Id and Also Take Date Column With Most Recent Value In Pandas按客户 ID 分组,并在 Pandas 中获取具有最新值的日期列
【发布时间】:2020-06-25 22:23:56
【问题描述】:

我是使用 Python 和 Pandas 的新手,我有一个关于对我拥有的日期框进行分组的问题。

我按 id 对数据框进行分组,但如果一个 id 有两行,我只想取 category_timestamp 列中具有最新值的行。

这是数据框中的结果:

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 的那个。

如何将它添加到这行代码中?

merged_df.groupby(['contact_id']) 

谢谢!

【问题讨论】:

  • 您可以通过排序和删除重复项来做到这一点,df.sort_values(by="category_timestamp", ascending=False).drop_duplicates(subset="id", keep="first")
  • this answer 中的第二个代码块也可以使用

标签: python pandas pandas-groupby


【解决方案1】:

我认为按日期对它们进行排序然后删除重复项会更容易。

df = df.sort_values('date_cancelled', ascending=False)
df = df.drop_duplicates(subset='owner_id', keep='first')
print(df) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-21
    • 2023-03-14
    • 2021-09-29
    • 1970-01-01
    • 2021-12-31
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多