0

I have simple data:

type age 
A    4   
A    4   
B    4   
A    5   

I want to get

type age count
A    4    2
A    5    1
B    4    1

How to perform such thing in panda: what shell I do after df.groupby(['type'])?

DuckQueen
  • 772
  • 10
  • 62
  • 134

2 Answers2

1

Let's use groupby with 'type' and 'age', then count and reset_index:

df.groupby(['type','age'])['age'].count().reset_index(name='count')

Output:

  type  age  count
0    A    4      2
1    A    5      1
2    B    4      1
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
0

You could also do

df.groupby(['type','age']).size().reset_index(name='count')
Gayatri
  • 2,197
  • 4
  • 23
  • 35