DataFrame:添加具有组大小的列 [英] DataFrame: add column with the size of a group
本文介绍了DataFrame:添加具有组大小的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据框:
fsq digits digits_type
0 1 1 odd
1 2 1 odd
2 3 1 odd
3 11 2 even
4 22 2 even
5 101 3 odd
6 111 3 odd
,我想添加最后一列 count ,其中包含属于 digits 组的 fsq 的数量,即:>
and I want to add a last column, count, containing the number of fsq belonging to the digits group, i.e:
fsq digits digits_type count
0 1 1 odd 3
1 2 1 odd 3
2 3 1 odd 3
3 11 2 even 2
4 22 2 even 2
5 101 3 odd 2
6 111 3 odd 2
因为有3个 fsq 行的 digits 等于1,所以有2个 fsq 行具有 digits 等于2,等等.
Since there are 3 fsq rows that has digits equal to 1, 2 fsq rows that has digits equal to 2, etc.
推荐答案
In [395]: df['count'] = df.groupby('digits')['fsq'].transform(len)
In [396]: df
Out[396]:
fsq digits digits_type count
0 1 1 odd 3
1 2 1 odd 3
2 3 1 odd 3
3 11 2 even 2
4 22 2 even 2
5 101 3 odd 2
6 111 3 odd 2
[7 rows x 4 columns]
这篇关于DataFrame:添加具有组大小的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文