How to merge multiple list into a single dataframe, replacing common values with 1 - Python

Viewed 23

I have multiple lists on python:

a = ["house","garden", "living room", "dog","cat"]

b= ["cat","dog", "chicken"]

c=["house", "garden","bathroom"]

I'd like to create the following dataframe:

a b c
house 0 1
garden 0 1
living room 0 0
dog 1 0
cat 1 0

Thanks for the help!

1 Answers

Create a single-column frame from a, then generate the remaining columns based on membership of a:

import pandas as pd

a = ["house","garden", "living room", "dog", "cat"]
b = ["cat","dog", "chicken"]
c = ["house", "garden", "bathroom"]

df = pd.DataFrame(data=a, columns=['a'])
df['b'] = [int(s in b) for s in a]
df['c'] = [int(s in c) for s in a]

print(df)

Which gives an output of:

             a  b  c
0        house  0  1
1       garden  0  1
2  living room  0  0
3          dog  1  0
4          cat  1  0
Related