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