【问题标题】:Group various columns in pandas with list of column values使用列值列表对 pandas 中的各个列进行分组
【发布时间】:2021-08-17 12:45:15
【问题描述】:

我有一个示例数据:

date       Product Advert_Type  total_clients
2020-01-01.  Dell.    call.       10
2020-01-01.  Dell.    Email.      5
2020-01-01.  Apple.   call.       6
2020-01-01.  Apple    fax.        4
2020-01-02.  Dell.    Email.      5
2020-01-02.  Dell.    fax.        4
2020-01-02.  Apple.   visit.      2
2020-01-02.  Apple.   call.       1

我想获得每个产品每月获得的客户总数以及每个产品类型在该月完成的事件列表。

输出应如下所示:

date       Product. Advert_Type.   Total_Clients
2020-01-01.  Dell.  [call,email].    15
2020-01-01.  Apple.  [call, fax].    10
2020-01-02.  Dell   [email, fax].     9
2020-01-02   Apple.  [visit, call].   3

【问题讨论】:

    标签: python pandas dataframe numpy data-science


    【解决方案1】:

    你可以使用groupby:

    df = df.groupby(['date', 'Product']).agg(
        {'Advert_Type': list, 'total_clients': sum}).reset_index()
    

    输出

              date Product      Advert_Type  total_clients
    0  2020-01-01.  Apple.    [call., fax.]             10
    1  2020-01-01.   Dell.  [call., Email.]             15
    2  2020-01-02.  Apple.  [visit., call.]              3
    3  2020-01-02.   Dell.   [Email., fax.]              9
    

    【讨论】:

      猜你喜欢
      • 2017-06-18
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 2013-05-27
      • 2021-10-30
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      相关资源
      最近更新 更多