0

I have a Python Pandas data frame like following:

movie        unknown action adventure animation fantasy horror romance sci-fi

Toy Story    0       1      1          0        1       0      0       1              
Golden Eye   0       1      0          0        0       0      1       0      
Four Rooms   1       0      0          0        0       0      0       0    
Get Shorty   0       0      0          1        1       0      1       0
Copy Cat     0       0      1          0        0       1      0       0 

I would like to combine the movie genres into one singe column. Output would be like this:

movie       genre

Toy Story   action, adventure, fantasy, sci-fy
Golden Eye  action, romance
Four Rooms  unknown
Get Shorty  animation, fantasy, romance
Copy Cat    adventure, horror

1 Answer 1

2

You can do it this way:

In [171]: df['genre'] = df.iloc[:, 1:].apply(lambda x: df.iloc[:, 1:].columns[x.astype(bool)].tolist(), axis=1)

In [172]: df
Out[172]:
        movie  unknown  action  adventure  animation  fantasy  horror  romance  sci-fi                                 genre
0   Toy Story        0       1          1          0        1       0        0       1  [action, adventure, fantasy, sci-fi]
1  Golden Eye        0       1          0          0        0       0        1       0                     [action, romance]
2  Four Rooms        1       0          0          0        0       0        0       0                             [unknown]
3  Get Shorty        0       0          0          1        1       0        1       0         [animation, fantasy, romance]
4    Copy Cat        0       0          1          0        0       1        0       0                   [adventure, horror]

PS but i don't understand how can it help you and i don't see any benefit compared to "one hot encoded" matrix

Sign up to request clarification or add additional context in comments.

1 Comment

df['genre'] = df.apply(lambda x: df.columns[x.astype(bool)].tolist()[1:], axis=1) +1 and agree that it wouldn't offer any additional benefit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.