Shape mismatch with manual categories in OrdinalEncoder

Viewed 1095

I am trying to encode an ordinal column by using the OrdinalEncoder from sklearn. Sample data could be the following:

from sklearn.preprocessing import OrdinalEncoder
import numpy as np
X = np.array([-1, -2, -3, 0, 1, 2, 3, 2, 1, 4, 1, 4, -1]).reshape(-1,1)

enc = OrdinalEncoder()
enc.fit(X)
enc.transform(X)

enc2 = OrdinalEncoder(categories = np.arange(-3, 5))
enc2.fit(X)
ValueError: Shape mismatch: if categories is an array, it has to be of shape (n_features,).

I want to be able to input the categories manually so the already existing question (Shape mismatch: if categories is an array, it has to be of shape (n_features,)) is not of much help. My problem is that I don't understand the error. The shape of the categories is (to my mind) correct:

np.arange(-3, 5).shape
Out [1]:(8,)

What am I missing?

1 Answers

From the help page:

Parameters
categories‘auto’ or a list of array-like, default=’auto’
Categories (unique values) per feature:

‘auto’ : Determine categories automatically from the training data.

list : categories[i] holds the categories expected in the ith column. The passed categories should not mix strings and numeric values, and should be sorted in case of numeric values.

So you need provide a list or array, and within it, each subelement would hold the categories. In your example, since there is only 1 column in the data to be fitted, it would be:

enc2 = OrdinalEncoder(categories = [np.arange(-3, 5)])
enc2.fit(X)
OrdinalEncoder(categories=[array([-3, -2, -1,  0,  1,  2,  3,  4])])
Related