Pandas check row list values with column name

Viewed 141

So i have a dataframe like:

enter image description here

and i want an output like:

enter image description here

The rows in df1 are nothing but combinations of the column names, wherever the combination name matches with the column names, that cell will be made as 1 and rest 0

Any idea how to achieve this?

I a trying to loop through each row and do a string contains condition but kind of stuck.

3 Answers

Here is a straightforward way (one-liner) of doing this using explode, get_dummies, and groupby

import pandas as pd
df = pd.DataFrame(['a',['a','b'],['a','b','c'], ['b','c','d'], ['b', 'd']])

multihot = pd.get_dummies(df.iloc[:,0].explode()).groupby(level=0).sum()
result = df.join(multihot)

print(result)
           0  a  b  c  d
0          a  1  0  0  0
1     [a, b]  1  1  0  0
2  [a, b, c]  1  1  1  0
3  [b, c, d]  0  1  1  1
4     [b, d]  0  1  0  1

Just make sure that the first column of your input df is the column that contains the lists.

This seems a bit hacky but should do the trick though:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.zeros((2, 4)), columns=["a", "b", "c", "d"], index=["a", ["a", "b"]])

pd.DataFrame(df.index.map(lambda l: pd.get_dummies(l, columns=df.columns).agg("sum")).tolist(), index=df.index).fillna(0)


#           a    b
# a       1.0  0.0
# [a, b]  1.0  1.0

I was able to do it using below code

df.reset_index(inplace=True)
for i in range(1,len(df.columns)):
    df.iloc[:, i]= df['index'].apply(lambda x: 1 if df.columns[i] in(x) else 0)

df
Related