0

in my dataframe i have a column 'amenities' and for each row this column contains a list of amenities.

enter image description here

My goal is basically to manually one-hot-encode this, i dont think what ive done is the most efficient way to write this code as it takes a little bit of time to run.

enter image description here

`

for amenity in amenities_list:
    amenities_df[amenity] = amenities_df['amenities'].apply(lambda x: 1 if amenity in str(x) else 0)

`

amenities_list is a list of all the amenities. The loop creates a new column for the amenity and then checks the amenities column and if that amenity is in the list then the individual column will show 1 otherwise 0.

I tried the above for loop but i'm thinking there's some better and more efficient way to preform the same action.

thanks

Theo B
  • 13
  • 3
  • Please add the dataframe in a way that can be copied into a text editor – Dani Mesejo Dec 17 '22 at 23:26
  • 3
    Please post code, errors, sample data or textual output here as plain-text, not as images that can be hard to read, can’t be copy-pasted to help test code or use in answers, and are barrier to those who depend on screen readers or translation tools. You can edit your question to add the code in the body of your question. For easy formatting use the `{}` button to mark blocks of code, or indent with four spaces for the same effect. The contents of a **screenshot can’t be searched, run as code, or easily copied and edited to create a solution.** – tadman Dec 17 '22 at 23:26
  • 1
    Is one of these solutions faster? https://stackoverflow.com/questions/29034928/pandas-convert-a-column-of-list-to-dummies – Nick ODell Dec 17 '22 at 23:43

0 Answers0