Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve order when label encoding

When label encoding numbers

[1, 1, 2, 6]

LabelEncoder return [0,0,1,2] because it sorts the classes

What's the best possible way to get [1,1,0,2] by preserving the original order

Tried - CategoricalIndex, which works the same way

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit([2, 1, 2, 6])

# le.classes_ [1,2,6]

le.transform([1, 1, 2, 6]) 

like image 443
user3055952 Avatar asked Jan 28 '26 22:01

user3055952


1 Answers

We can using factorize

pd.factorize([2, 1, 2, 6])[0]
array([0, 1, 0, 2])
like image 139
BENY Avatar answered Jan 31 '26 09:01

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!