python group by 和 count() 多列 [英] python group by and count() multiple columns

查看:150
本文介绍了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

这篇关于python group by 和 count() 多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆