【问题标题】:Aggregate & arrange results in dataframe by two criteria通过两个标准在数据框中聚合和排列结果
【发布时间】:2021-05-13 06:52:55
【问题描述】:

我有以下用于电子邮件活动活动的 Excel 表:

我想跟踪每个客户的每个 email_title 活动并按日期安排。

到目前为止我对数据框所做的工作:

我过滤了 customer_email 列表以获得唯一数量的电子邮件:

Unique_emails = df.email.unique()

然后为 email_title 和 Status 过滤每个 customer_email 的活动:

activity = ['delivered','opened']
for emails in Unique_emails:
    email_titles = df.loc[(df['customer_email'] == emails) & (df['status'].isin(activity)), ['email_title','date','status']]

现在,我想要汇总每个客户的每个 email_title 的状态。

挑战是每个客户都有相同的 email_title,前 3 行显示电子邮件“在 15 分钟内提升您的技能”已发送到 email1@sample.com 2 次​​p>

首先 - 20 年 1 月 1 日交付并打开(这是一项活动) 然后是第二个 - 2020 年 2 月 1 日交付但未打开

现在我想汇总每个客户每个日期的每个 email_title

我怎样才能做到这一点?我不是数据框专家

谢谢

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    对于这种特定情况,因为o 在字母表中位于n 之后,您可以简单地使用max 来查看openednot opened 是否应该是每行所需的输出,它看起来像您需要将last 用于status 列,该列查找组的最后一个值,这取决于排序。

    输入数据:

    df = pd.DataFrame({'date': {0: '1/1/2020', 1: '1/1/2020', 2: '2/1/2020'},
     'customer_email': {0: 'email1@sample.com',
      1: 'email1@sample.com',
      2: 'email1@sample.com'},
     'email_title': {0: 'Elevate your skills in 15 minutes',
      1: 'Elevate your skills in 15 minutes',
      2: 'Elevate your skills in 15 minutes'},
     'status': {0: 'opened', 1: 'delivered', 2: 'delivered'}})
    df
    

    代码:

    (df.assign(**{'new status aggregrated per email title' : df['status'].replace('delivered', 'not opened')})
       .groupby(['date', 'customer_email', 'email_title'], as_index=False)
       .agg({'status' : 'last', 'new status aggregrated per email title' : 'max'}))
    

    输出:

           date     customer_email                        email_title     status  \
    0  1/1/2020  email1@sample.com  Elevate your skills in 15 minutes  delivered   
    1  2/1/2020  email1@sample.com  Elevate your skills in 15 minutes  delivered   
    
      new status aggregrated per email title  
    0                                 opened  
    1                             not opened  
    

    【讨论】:

    • 谢谢大卫,这正是我想要的,但我遇到了另一个问题,如果电子邮件在特定日期发送然后在另一个日期打开 - 这不会聚合这个特定的 email_title。知道我该怎么做吗?再次感谢
    • @Mtaly 如果您希望每行拥有latest status,您可以执行以下操作:df['latest status'] = df.groupby(['customer_email', 'email_title'])['status'].transform('last')。从那里,您可以调整上面的代码以到达您的端点。
    猜你喜欢
    • 2021-12-12
    • 2020-09-25
    • 2019-10-19
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    相关资源
    最近更新 更多