'How to use OrdinalEncoder() to set custom order?

I have a column in my Used cars price prediction dataset named "Owner_Type". It has four unique values which are ['First', 'Second', 'Third', 'Fourth']. Now the order that makes the most sense is First > Second > Third > Fourth as the price decreases with respect to this order. How can I give this order to the values with OrdinalEncoder()? Please help me, thank you!



Solution 1:[1]

OrdinalEncoder have a parameter categories which can accept list of array of categories. here a code example:

from sklearn.preprocessing import OrdinalEncoder
enc = OrdinalEncoder(categories=[['first','second','third','forth']])
X = [['third'], ['second'], ['first']]
enc.fit(X)
print(enc.transform([['second'], ['first'], ['third'],['forth']]))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ghassen Sultana