如何创建一个名为“ Count”的新列,以使每行包含相应行的已注册“性别”的计数。例如,在下面的示例中,有2个注册女性和1个注册男性,因此用于输入:
Gender Registered
female 1
female 1
female 0
male 1
male 0
male 0
输出应为:
Gender Registered Count
female 1 2
female 1 2
female 0 2
male 1 1
male 0 1
male 0 1
我尝试了类似的方法,但是没有用:
df[df['Registered'] == 1].groupby('Gender')['Gender'].count()
答案 0 :(得分:2)
使用transform
df.groupby('Gender').Registered.transform(lambda x : sum(x==1))
0 2
1 2
2 2
3 1
4 1
5 1
Name: Registered, dtype: int64
#df['count']=df.groupby('Gender').Registered.transform(lambda x : sum(x==1))