0

I have used the groupby method on a Pandas Dataframe and I want to convert the result to a DataFrame. I have used unstack but it only converts the results to features and not a proper dataframe.

I have tried approaches answered in other SO Questions like this but it was not useful.

Original DataFrame - badges

UserId      Class   
-1      |   B
-1      |   B
1       |   A   
100     |   A   
100     |   B
102     |   B   
102     |   B
107     |   A

Code
badges = badges.groupby('UserId')['Class'].value_counts().unstack().fillna(0)

Output

Class        A  |  B    
UserId          
-1      |   0.0 | 2.0   
1       |   1.0 | 0.0   
100     |   1.0 | 1.0   
102     |   0.0 | 2.0   
107     |   1.0 | 0.0   

Required Output

UserId  |    A  |  B
    
-1      |   0.0 | 2.0   
1       |   1.0 | 0.0   
100     |   1.0 | 1.0   
102     |   0.0 | 2.0   
107     |   1.0 | 0.0
Ishan Dutta
  • 897
  • 4
  • 16
  • 36

0 Answers0