DEV Community

Faruq Sandi
Faruq Sandi

Posted on

Answer: how to make one hot encoding to column in data frame in python

You need to set sparse to False

from sklearn.preprocessing import OneHotEncoder

onehot_encoder = OneHotEncoder(sparse=False)
y_train = np.random.randint(0,4,100)[:,None]
y_train = onehot_encoder.fit_transform(y_train)

Or, you can also do something like this

from sklearn.preprocessing import LabelEncoder
from keras.utils import np_utils

y_train = np.random.randint(0,4,100)
encoder = LabelEncoder()
encoder.fit(y_train)
encoded_y = encoder.transform(y_train)
y_train = np_utils.to_categorical(encoded_y)

Top comments (0)