How i match string value from a column to other column name in python

Viewed 51

Dataframe:

MovieID movieCater
1 Action, Comedy, Adventure
2 Action, Crime
3 Crime

What I want:

MovieID movieCater Action Comedy Adventure Crime
1 Action, Comedy, Adventure 1 1 1 0
2 Action, Crime 1 0 0 1
3 Crime 0 0 0 1

my data frame does not include action, comedy, and others columns. is there any method that makes that happen? for example the first of movieCater include action, comedy, and adventure. then go to the corresponding column name and set it to 1.

1 Answers

Try this:

df_original = df.copy()
df['movieCater'] = df['movieCater'].str.split(', ')
df = df.explode('movieCater')
df['value'] = 1
df_original.join(df.pivot(columns=['movieCater'], values=['value']).fillna(0).droplevel(0,axis=1))

#   MovieID                 movieCater  Action  Adventure  Comedy  Crime
# 0        1  Action, Comedy, Adventure     1.0        1.0     1.0    0.0
# 1        2              Action, Crime     1.0        0.0     0.0    1.0
# 2        3                      Crime     0.0        0.0     0.0    1.0
Related