StackUser
StackUser

Reputation: 475

Group various columns in pandas with list of column values

I have an example data as:

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

I would like to get the total clients obtained for each products on a monthly basis and the list of events done in that month fo each prodcut type.

The output should look like this:

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

Upvotes: 1

Views: 29

Answers (1)

Nk03
Nk03

Reputation: 14949

You can use groupby:

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

OUTPUT

          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

Upvotes: 1

Related Questions