user3447653
user3447653

Reputation: 4158

Convert a pandas dataframe column values into column names

I have a pandas dataframe in the below format:

       no     point1    point2  point3    
  1    101    roof      garage  basement  
  2    102    basement  garage  painting

I am trying to go over the above pandas dataframe and come up with a below dataframe. For example, for no "101", if "roof" is present, I would need to populate it with "1" in df_final, if not it has to be populated with "0".

df_final = ['no','roof','garage','basement']

df_final:

     no   roof  garage  basement    painting
1    101    1       1       1           0
2    102    0       1       1           1

Not sure whether there is a functionality to convert it into the above format. Any suggestions would be appreciated.

Upvotes: 1

Views: 63

Answers (1)

noah
noah

Reputation: 2776

Use get_dummies() (Docs):

pd.get_dummies(df)

Alternatively if you want it all "nicely combined":

pd.get_dummies(df,prefix='', prefix_sep='').groupby(level=0, axis=1).max().set_index("no")

Upvotes: 2

Related Questions