Python pandas:在我的数据框中添加一列来计算一个变量 [英] Python pandas: Add a column to my dataframe that counts a variable

查看:2165
本文介绍了Python pandas:在我的数据框中添加一列来计算一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框'gt':

I have a dataframe 'gt' like this:

org     group
org1      1
org2      1
org3      2
org4      3
org5      3
org6      3

,我想添加column'count'到gt dataframe来计算组的成员数量,这样的预期结果:

and I would like to add column 'count' to gt dataframe to counts number member of the groups, expected results like this:

org     group   count
org1      1       2
org2      1       2
org3      2       1
org4      3       3
org5      3       3
org6      3       3

我知道如何对群组中的每一项操作,但不知道如何计算重复所有的组项目,这里是我使用的代码:

I know how to do it per one item of the group, but do not know how to make the count repeated for all of the group items, here is the code I have used:

gtcounts = gt.groupby('group').count()

任何人都可以帮忙吗?

Can anybody help?

推荐答案

请致电 transform 这将返回一个与原始df对齐的系列:

Call transform this will return a Series aligned with the original df:

In [223]:

df['count'] = df.groupby('group')['group'].transform('count')
df
Out[223]:
    org  group  count
0  org1      1      2
1  org2      1      2
2  org3      2      1
3  org4      3      3
4  org5      3      3
5  org6      3      3

这篇关于Python pandas:在我的数据框中添加一列来计算一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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