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

﹥>﹥吖頭↗ 提交于 2020-04-09 19:36:33

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/50422809/pandas-group-by-with-all-the-values-of-the-group-as-comma-separated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!