python group by and count() multiple columns

六眼飞鱼酱① 提交于 2021-02-08 05:03:37

问题


I have a data frame like this:

Country  A B C
UK       1 0 1
US       1 1 1
GB       0 1 1
UK       1 1 1
US       0 1 1
GB       0 1 1

I need to groupby country and count in all columns where value is 1. I'm stuck on setting the condition of columns == 1 for all them.

The result should be something like:

Country  A B C
UK       2 0 2
US       1 2 2
GB       0 2 2

回答1:


Because you are counting 1's you can just groupby([]).sum()

df['country'] = df.index # to generate a new column
result = df.groupby(['country']).sum()

This gives you the result:

         a  b  c
country         
GB       0  2  2
UK       2  1  2
US       1  2  2

More information https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html



来源:https://stackoverflow.com/questions/58161230/python-group-by-and-count-multiple-columns

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