如何在python中创建一个列,该列统计另一列中的出现次数,而不聚合行?
我需要计算列中特定元素的出现次数,并将出现次数作为附加列添加,而不删除行 我试过了如何在python中创建一个列,该列统计另一列中的出现次数,而不聚合行?,python,pandas,Python,Pandas,我需要计算列中特定元素的出现次数,并将出现次数作为附加列添加,而不删除行 我试过了 df['counts']=df.no.value\u counts() df['counts']=df.groupby(no_41;.count() O21['count']=df.groupby('no_979;')。transform('count')) 这就是我所拥有的: id|no| --------- 1 | 1 | 2 | 3 | 3 | 3 | 4 | 4 | 5 |
df['counts']=df.no.value\u counts()
df['counts']=df.groupby(no_41;.count()
O21['count']=df.groupby('no_979;')。transform('count'))
这就是我所拥有的:
id|no|
---------
1 | 1 |
2 | 3 |
3 | 3 |
4 | 4 |
5 | 2 |
理想情况下,我希望它看起来像这样
id|no_ |count(no_)|
---------------
1 | 1 | 1 |
2 | 3 | 2 |
3 | 3 | 2 |
4 | 4 | 1 |
5 | 2 | 1 |
您已关闭,需要在
groupby
之后指定列:
df['count'] = df.groupby('no_')['no_'].transform('count')
或者使用映射
:
df['counts']= df.no_.map(df.no_.value_counts())
print (df)
id no_ counts
0 1 1 1
1 2 3 2
2 3 3 2
3 4 4 1
4 5 2 1