问题
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