我有一个像这样的数据框:
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。
结果应该类似于:
Country A B C
UK 2 0 2
US 1 2 2
GB 0 2 2
答案 0 :(得分:2)
由于您要数1,因此您可以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