LamaMo
LamaMo

Reputation: 626

Count the number of element within each group

I have this dataframe df, which includes name and type columns:

name   type
Jay    c1
Rand   c2
Hano   c3
Jay    c1
Jay    c2
Rand   c2
Roger  c1
Roger  c1
Roger  c3

The output should be like that (for each of the type, how many each name; inserted as a new column):

name   type   count
Jay    c1     2
Jay    c2     1
Rand   c2     2
Hano   c3     1
Roger  c1     2
Roger  c3     1

Upvotes: 0

Views: 47

Answers (1)

Mayank Porwal
Mayank Porwal

Reputation: 34046

Use:

In [1060]: df.groupby(['name', 'type']).size().reset_index(name='count')
Out[1060]: 
    name type  count
0   Hano   c3      1
1    Jay   c1      2
2    Jay   c2      1
3   Rand   c2      2
4  Roger   c1      2
5  Roger   c3      1

Upvotes: 2

Related Questions