Problem with Changing Categorical variable with OneHotEncoding

Viewed 50

I have a column gender with values male (1) and female (0). When I use the following code to onehotencode the gender column:

onehotencoder = OneHotEncoder(categorical_features=['gender'])
data = onehotencoder.fit_transform(data).toarray()

I get the following error:

IndexError: arrays used as indices must be of integer (or boolean) type
1 Answers

The following description can be found in the documentation of OneHotEncoder :

categorical_features : ‘all’ or array of indices or mask, default=’all’ Specify what features are treated as categorical. ‘all’: All features are treated as categorical. array of indices: Array of categorical feature indices. mask: Array of length n_features and with dtype=bool.

So instead of passing the name of your column you should pass the index of your column and that should solve your problem.


By the way, pay attention to the deprecation stated in the documentation :
Deprecated since version 0.20: The categorical_features keyword was deprecated in version 0.20 and will be removed in 0.22. You can use the ColumnTransformer instead.

Related