0
$\begingroup$

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.

$\endgroup$
2
  • 1
    $\begingroup$ there is no theoretical problem if it suits your application $\endgroup$ – Nikos M. May 5 at 19:56
  • 1
    $\begingroup$ No I am asking how to perform this conversion using pandas or keras APIs. $\endgroup$ – tensirflow May 5 at 20:15
1
$\begingroup$

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 )
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.