# How to create multi-hot encoding from a list column in dataframe?

I have dataframe like this

Label   IDs
0   [10, 1]
1   [15]
0   [14]


I want to create a multihot encoding of the feature IDs. It should look like this

Label ID_10 ID_1 ID_15 ID_14
0     1     1    0     0
1     0     0    1     0
0     0     0    0     1


The goal is to use them as features in Keras. So it is also acceptable to make this transformation using a Keras API.

• there is no theoretical problem if it suits your application May 5, 2021 at 19:56
• No I am asking how to perform this conversion using pandas or keras APIs. May 5, 2021 at 20:15

You can try using sklearn's MultiLabelBinarizer (https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html):

mlb = MultiLabelBinarizer()
mlb.fit(d['IDs'])

new_col_names = ["ID_%s" % c for c in mlb.classes_]

# Create new DataFrame with transformed/one-hot encoded IDs
ids = pd.DataFrame(mlb.fit_transform(d['IDs']), columns=new_col_names)

# Concat with original Label column
pd.concat( [d[['Label']], ids], axis=1 )