Pandas: How to count Occurrences of Categorical features Grouped by ID

Viewed 2899

Suppose I have this DataFrame df

My_ID   My_CAT
  1       A
  2       B  
  3       C
  1       A  
  1       B 
  2       D 

I'd like to know how many occurrences of each distinct My_Cat value occurs for each distinct My_ID.

I need it in the form of a dense array like

My_ID   A    B    C   D
  1     2    1    0   0
  2     0    1    0   1
  3     0    0    1   0

I tryd with

df.groupby(['My_ID','My_CAT']).count()

but although I see data are grouped accordingly to my need occurrences are not counted.

2 Answers
Related