python group by 和 count() 多列
问题描述:
我有一个这样的数据框:
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
我需要按国家/地区分组并计算值为 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.
结果应该是这样的:
Country A B C
UK 2 0 2
US 1 2 2
GB 0 2 2
答
因为你在数 1,所以你可以 groupby([]).sum()
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()
结果如下:
a b c
country
GB 0 2 2
UK 2 1 2
US 1 2 2
更多信息https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html