Pandas 新列中的组计数
我想要一个新的栏目“组计数”。这将在中显示该属性总共出现了多少组。Pandas 新列中的组计数,pandas,group-by,Pandas,Group By,我想要一个新的栏目“组计数”。这将在中显示该属性总共出现了多少组。 Group Attribute group_count 0 1 10 4 1 1 10 4 2 1 10 4 3 2 10 4 4 2 20
Group Attribute group_count
0 1 10 4
1 1 10 4
2 1 10 4
3 2 10 4
4 2 20 1
5 3 30 1
6 3 10 4
7 4 10 4
我尝试按组和属性分组,然后使用计数进行转换
df["group_count"] = df.groupby(["Group", "Attributes"])["Attributes"].transform("count")
Group Attribute group_count
0 1 10 3
1 1 10 3
2 1 10 3
3 2 10 1
4 2 20 1
5 3 30 1
6 3 10 1
7 4 10 1
但是它不起作用与转换一起使用
:
df['group_count1'] = df.groupby('Attribute')['Group'].transform('nunique')
print (df)
Group Attribute group_count group_count1
0 1 10 4 4
1 1 10 4 4
2 1 10 4 4
3 2 10 4 4
4 2 20 1 1
5 3 30 1 1
6 3 10 4 4
7 4 10 4 4
使用
df.drop_duplicates(['Group','Attribute'])
获得每个组的唯一属性
,然后在属性上groupby
获得组的计数
,最后将映射到原始属性
列
m=df.drop_duplicates(['Group','Attribute'])
df['group_count']=df['Attribute'].map(m.groupby('Attribute')['Group'].count())
print(df)
有一个小错误:它是value_counts()@jezrael谢谢你的回复。我更新了我的问题。我想知道该属性出现在多少组中。因此,在属性为10的行中,它总共出现在4个组中。
Group Attribute group_count
0 1 10 4
1 1 10 4
2 1 10 4
3 2 10 4
4 2 20 1
5 3 30 1
6 3 10 4
7 4 10 4