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
  • 100
  • 8
  • 52
  • 121

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
  • 133,446
  • 13
  • 126
  • 161
0

You could also do

df.groupby(['type','age']).size().reset_index(name='count')
Gayatri
  • 2,037
  • 2
  • 22
  • 32