pythonpandas添加一列_Python pandas:在我的数据框中添加一列来计算一个变量

I have a dataframe 'gt' like this:

org group

org1 1

org2 1

org3 2

org4 3

org5 3

org6 3

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?

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值