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