1

My dataframe has a column with some values, these values can apper in all rows, but is not required. I want to split this values in different rows, putting 1 if the value apper in that column

I am using python 3 and the df is:

data = {'Amenities':[{'TV', 'Wifi'}, {'TV',"Cable TV",'Internet','Wifi'}, {'Internet','Wifi'}]} df2 = pd.DataFrame(data) df2 Amenities 0 {TV, Wifi} 1 {TV, Cable TV, Wifi, Internet} 2 {Wifi, Internet} 

I would like to see a table in this way:

data = {'Amenities':[{'TV', 'Wifi'}, {'TV',"Cable TV",'Internet','Wifi'}, {'Internet','Wifi'}], 'TV':[1,1,0], 'Cable TV':[0,1,0], 'Wifi':[1,1,1], 'Internet':[0,1,1], } df2 = pd.DataFrame(data) df2 Amenities TV Cable TV Wifi Internet 0 {TV, Wifi} 1 0 1 0 1 {TV, Cable TV, Wifi, Internet} 1 1 1 1 2 {Wifi, Internet} 0 0 1 1 

1 Answer 1

1

In your case using get_dummies then concat

s=pd.get_dummies(df2.Amenities.apply(list).apply(pd.Series),prefix = '',prefix_sep = '').sum(level=0,axis=1) s Out[66]: Cable TV Internet TV Wifi 0 0 0 1 1 1 1 1 1 1 2 0 1 0 1 df=pd.concat([df2,s],axis=1) df Out[68]: Amenities Cable TV Internet TV Wifi 0 {TV, Wifi} 0 0 1 1 1 {Cable TV, Internet, Wifi, TV} 1 1 1 1 2 {Internet, Wifi} 0 1 0 1 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.