Pandas group by one hot encoded columns

Viewed 59

I have my Pandas data frame in the following way (basically one hot encoded columns):

 MovieID Action  Adventure  Animation  Childrens  Comedy  Crime  Documentary  rating
  1        0          0          1          1       1      0            0     4   
  2        1          0          0          0       1      0            0     5   
  3        0          0          0          0       0      1            0     2   
  4        0          0          0          0       0      0            0     4   
  5        0          0          0          1       1      0            0     7  

What I want to do it group by the different movie genres (action, adventure, animation etc.) and count how many times there was a rating given for each of the genres.

Expected output:

Genre       Number of times rated
Action             1
Adventure          0
Animation          1
Childrens          2
Comedy             3
......

Genre Action was rated 1 time, adventure 0 times etc.

Code until now:

number_of_ratings = data.groupby(['Action']).agg({"rating": "count"})

Is there a way to select all genre columns at once, as it does not seem ideal to type all the genres (they are much more)?

Does it handle the fact that some of the movies belong to more genres?

Thank you in advance!

1 Answers

Sounds like we can try

output = df.drop(['MovieID', 'rating'], axis=1).sum()
Action         1
Adventure      0
Animation      1
Childrens      2
Comedy         3
Crime          1
Documentary    0
dtype: int64
Related