Vineet
Vineet

Reputation: 1572

Pandas | Group by with all the values of the group as comma separated

As per application requirement, I need to show all the data which is part of group by in comma separated format so the admin can take decision, I am new to Python and not sure how to do it.

Sample reproducible data

import pandas as pd

compnaies = ['Microsoft', 'Google', 'Amazon', 'Microsoft', 'Facebook', 'Google']
products = ['OS', 'Search', 'E-comm', 'X-box', 'Social Media', 'Android']

df = pd.DataFrame({'company' : compnaies, 'product':products })
-----------------------------------------------------------------   
    company     product
0   Microsoft   OS
1   Google      Search
2   Amazon      E-comm
3   Microsoft   X-box
4   Facebook    Social Media
5   Google      Android

Now I getting count of company group by this code

df.groupby(['company']).count()

I need data in below mentioned format but not sure how to get it

Desired output

company    count product
Amazon      1    E-comm
Facebook    1    Social Media
Google      2    Search, Android
Microsoft   2    OS, X-box

Upvotes: 14

Views: 16403

Answers (1)

llllllllll
llllllllll

Reputation: 16424

You can use:

In [35]: df.groupby('company').product.agg([('count', 'count'), ('product', ', '.join)])
Out[35]: 
           count          product
company                          
Amazon         1           E-comm
Facebook       1     Social Media
Google         2  Search, Android
Microsoft      2        OS, X-box

Upvotes: 31

Related Questions