0
$\begingroup$

I already posted this here but no response, so posting it here

I have a dataframe like as shown below

tdf = pd.DataFrame({'grade': np.random.choice(list('AAAD'),size=(5)),
                   'dash': np.random.choice(list('PPPS'),size=(5)),
                   'dumeel': np.random.choice(list('QWRR'),size=(5)),
                   'dumma': np.random.choice((1234),size=(5)),
                   'target': np.random.choice([0,1],size=(5))
})

I would like to get a mapping dictionary based on ordinal encoding technique as given here

from feature_engine.encoding import OrdinalEncoder
X = tdf.drop(['target'], axis=1)
y = tdf.target
train_t, test_t, y_train, y_test = train_test_split(X, y, 
                                                test_size=0.25,
                                                random_state=0)
cat_list= tdf.select_dtypes(include=['object']).columns.tolist()
ordinal_encoders = {}
for col in cat_list:
    print(col)
    ordi = OrdinalEncoder(encoding_method='ordered')
    ordinal_encoders[col] = ordi
    ordi.fit(train_t[col], y_train)
    train_t[col] = ordi.transform(train_t[col])

However, I get the below error

TypeError: X is not a pandas dataframe. The dataset should be a pandas dataframe.

How can I fit and transform the ordinal encoder on a column by column basis? I am able to get the encoders initialized as shown below but unable to fit and transform them

{'grade': OrdinalEncoder(),
 'dash': OrdinalEncoder(),
 'dumeel': OrdinalEncoder()}

I would like to do it this way because later, I wish to finally get the mapping dictionary (ordinal value for each of the catgories and store it in a dictionary)

$\endgroup$

1 Answer 1

1
$\begingroup$

that is because train_t[col] in the last two lines return a pandas Series object rather than a pandas DataFrame. Use train_t.loc[:, [col]] instead.

all in all, to fix your issue, replace the last for loop with:

for col in cat_list:
    print(col)
    ordi = OrdinalEncoder(encoding_method='ordered')
    ordinal_encoders[col] = ordi
    ordi.fit(train_t.loc[:, [col]], y_train)
    train_t[col] = ordi.transform(train_t.loc[:, [col]])
$\endgroup$
1
  • $\begingroup$ thanks, upvoted..welcome to the forum $\endgroup$
    – The Great
    Feb 3 at 3:33

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.