You were almost there !

Basically the fit method, prepare the encoder (fit on your data i.e. prepare the mapping) but don't transform the data.

You have to call transform to transform the data , or use fit_transform which fit and transform the same data.

enc = OrdinalEncoder()
enc.fit(df[["Sex","Blood", "Study"]])
df[["Sex","Blood", "Study"]] = enc.transform(df[["Sex","Blood", "Study"]])

or directly

enc = OrdinalEncoder()
df[["Sex","Blood", "Study"]] = enc.fit_transform(df[["Sex","Blood", "Study"]])

Note: The values won't be the one that you provided, since internally the fit method use numpy.unique which gives result sorted in alphabetic order and not by order of appearance.

As you can see from enc.categories_

[array(['F', 'M'], dtype=object),
 array(['A', 'AB', 'B', 'O'], dtype=object),
 array(['Biology', 'English', 'Math', 'Science'], dtype=object)]```

Each value in the array is encoded by it's position. (F will be encoded as 0 , M as 1)

Answer from abcdaire on Stack Overflow
🌐
scikit-learn
scikit-learn.org › stable › modules › generated › sklearn.preprocessing.OrdinalEncoder.html
OrdinalEncoder — scikit-learn 1.9.1 documentation
By default, OrdinalEncoder is lenient towards missing values by propagating them. >>> import numpy as np >>> X = [['Male', 1], ['Female', 3], ['Female', np.nan]] >>> enc.fit_transform(X) array([[ 1., 0.], [ 0., 1.], [ 0., nan]]) You can use the parameter encoded_missing_value to encode missing values.
Top answer
1 of 5
48

You were almost there !

Basically the fit method, prepare the encoder (fit on your data i.e. prepare the mapping) but don't transform the data.

You have to call transform to transform the data , or use fit_transform which fit and transform the same data.

enc = OrdinalEncoder()
enc.fit(df[["Sex","Blood", "Study"]])
df[["Sex","Blood", "Study"]] = enc.transform(df[["Sex","Blood", "Study"]])

or directly

enc = OrdinalEncoder()
df[["Sex","Blood", "Study"]] = enc.fit_transform(df[["Sex","Blood", "Study"]])

Note: The values won't be the one that you provided, since internally the fit method use numpy.unique which gives result sorted in alphabetic order and not by order of appearance.

As you can see from enc.categories_

[array(['F', 'M'], dtype=object),
 array(['A', 'AB', 'B', 'O'], dtype=object),
 array(['Biology', 'English', 'Math', 'Science'], dtype=object)]```

Each value in the array is encoded by it's position. (F will be encoded as 0 , M as 1)

2 of 5
34

I think it is important to point out that this is not an example for an ordinal encoding of variables. Sex, Blood and Study should all not have an ordinal scale (and was also not suggested by the person, who asked the question). Ordinal data has a ranking (see e.g. https://en.wikipedia.org/wiki/Ordinal_data) Those examples here do not have a ranking.

In the case that your variable is a target variable you can use the LabelEncoder.(https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html)

Then you can do something like:

from sklearn.preprocessing import LabelEncoder

for col in ["Sex","Blood", "Study"]:
    df[col] = LabelEncoder().fit_transform(df[col])

If your variables are features you should use the Ordinalencoder for accomplishing this. (See comments to my answer).

The naming for the Ordinalencoder is quite unfortunate as "ordinal" is seen from a mathematical and not a statistical naming perspective.

More on the difference between ordinal- and labelencoder in sklearn: https://datascience.stackexchange.com/questions/39317/difference-between-ordinalencoder-and-labelencoder

🌐
Educative
educative.io › answers › ordinal-encoding-in-python
Ordinal encoding in Python
Lines 2–3: We import the required libraries, including pandas for data manipulation and the OrdinalEncoder package from the scikit-learn library for ordinal encoding. Line 6: We create a sample DataFrame (df) with a categorical column named Colors. Line 14: We initialize the OrdinalEncoder class.
🌐
MachineLearningMastery
machinelearningmastery.com › home › blog › ordinal and one-hot encodings for categorical data
Ordinal and One-Hot Encodings for Categorical Data - MachineLearningMastery.com
August 17, 2020 - This ordinal encoding transform is available in the scikit-learn Python machine learning library via the OrdinalEncoder class.
🌐
ProjectPro
projectpro.io › recipes › encode-ordinal-categorical-features-in-python
Ordinal Encoding - What, How, and When? -
April 1, 2024 - These two lines of code will help you encode your categorical data into a numerical format using ordinal encoding in Python.
🌐
Medium
leochoi146.medium.com › how-and-when-to-use-ordinal-encoder-d8b0ef90c28c
How and When to Use Ordinal Encoder | by Leo Choi | Medium
April 21, 2021 - This is a brief guide aimed at helping you determine whether or not you should use an ordinal encoder for your category encoding. Near the bottom of this post, there are examples of how to use OrdinalEncoder from the category_encoders library in Python.
🌐
GeeksforGeeks
geeksforgeeks.org › machine learning › how-to-perform-ordinal-encoding-using-sklearn
How to Perform Ordinal Encoding Using Sklearn - GeeksforGeeks
August 5, 2025 - Let's see the implementation of Ordinal Encoding using Sklearn with the help of examples, Step 1: Import libraries · Import Pandas and Scikit learn · Python · from sklearn.preprocessing import OrdinalEncoder import pandas as pd !pip install scikit - learn ·
🌐
Trainindata
feature-engine.trainindata.com › en › latest › user_guide › encoding › OrdinalEncoder.html
Ordinal Encoding — 1.9.4 - Feature-engine
This encoding method assigns numbers to the categories based on their order of appearance in the dataset, incrementing the value for each new category encountered. Assigning ordinal numbers arbitrarily provides a simple way of obtaining numerical variables from categorical data and it tends ...
Find elsewhere
🌐
Trainindata
feature-engine.trainindata.com › en › 1.8.x › user_guide › encoding › OrdinalEncoder.html
Ordinal Encoding — 1.8.3
This method helps machine learning algorithms, particularly linear models (like linear regression), better capture and learn the relationship between the encoded feature and the target. Keep in mind that ordered ordinal encoding will create a monotonic relationship between the encoded variable and the target variable only when there is an intrinsic relationship between the categories and the target variable.
🌐
MachineLearningMastery
machinelearningmastery.com › home › blog › decision trees and ordinal encoding: a practical guide
Decision Trees and Ordinal Encoding: A Practical Guide - MachineLearningMastery.com
February 28, 2025 - By implementing ordinal encoding using Python and the OrdinalEncoder from sklearn, you’ve prepared the Ames dataset in a way that respects the inherent order of the data.
🌐
Scaler
scaler.com › home › topics › data-science › ordinal encoding
Ordinal Encoding - Scaler Topics
May 4, 2023 - Let’s understand how you can apply ordinal encoding to categorical features using Python libraries.
🌐
YouTube
youtube.com › watch
Ordinal Encoder with Python Machine Learning (Scikit-Learn) - YouTube
🧠 Don’t miss out! Get FREE access to my Skool community — packed with resources, tools, and support to help you with Data, Machine Learning, and AI Automati...
Published: August 15, 2023
Top answer
1 of 4
5

The main distinction between LabelEncoder and OrdinalEncoder is their purpose:

  • LabelEncoder should be used for target variables,
  • OrdinalEncoder should be used for feature variables.

In general they work the same, but:

  • LabelEncoder needs y: array-like of shape [n_samples],
  • OrdinalEncoder needs X: array-like, shape [n_samples, n_features].

If you just want to encode your categorical variable's values to 0, 1, ..., n, use LabelEncoder the same way you did with X1 and X2.

labelencoder_X_3 = LabelEncoder()
X[:, 2] = labelencoder_X_3.fit_transform(X[:, 2])

But I would transform all three variables with OrdinalEncoder at the same time:

ordinalencoder_X = OrdinalEncoder()
X[:, 0:3] = ordinalencoder_X.fit_transform(X[:, 0:3])
2 of 4
2

Instead of using Ordinal Encoder, One other option is to use Pandas Applymap function and pass the mapping dictionary using Lambda Function.

Here is the mapping dictionary:

mapping = { "Tiny Mongra" : 0,"Mini Mongra" : 1,"Mongra":2,"Super Mongra" : 3,"Mini 
Dubar":4,"Dubar":5,"Super Dubar":6,"Mini Tibar":7,"Tibar":8,"Super Tibar":9,"2nd 
Wand":10,"Super 2nd Wand" :11,"1st Wand":12}

Lets say below is my dataframe:

df = pd.DataFrame(['Tiny Mongra', 'Mini Dubar' ,'Mongra', '1st Wand' ,'1st Wand' 
,'Dubar' ,'2nd Wand','Tibar', 'Mongra', 'Super Dubar', '1st Wand', '1st Wand', '1st 
 Wand' ,'1st Wand','1st Wand', '2nd Wand' ,'Super Dubar' ,'Super Tibar' ,'1st Wand', 
'1st Wand'],   columns = ['category'])

Then you can create another encoded mapping column using below code:

df['mapped_category'] = df.applymap(lambda x : mapping[x])
🌐
Stackademic
blog.stackademic.com › how-to-use-ordinal-encoding-in-python-240254d1bbf1
2 Easy Steps to Use Ordinal Encoding in Python | by Shashanka Shekhar | Stackademic
April 10, 2024 - Python is a high-level, general-purpose ... library and dynamic semantics. Ordinal encoding is a preprocessing technique used for converting categorical data into numeric values that preserve their inherent ordering....
🌐
scikit-learn
scikit-learn.org › dev › modules › generated › sklearn.preprocessing.OrdinalEncoder.html
OrdinalEncoder — scikit-learn 1.10.dev0 documentation
By default, OrdinalEncoder is lenient towards missing values by propagating them. >>> import numpy as np >>> X = [['Male', 1], ['Female', 3], ['Female', np.nan]] >>> enc.fit_transform(X) array([[ 1., 0.], [ 0., 1.], [ 0., nan]]) You can use the parameter encoded_missing_value to encode missing values.
🌐
scikit-learn
scikit-learn.org › 1.5 › modules › generated › sklearn.preprocessing.OrdinalEncoder.html
OrdinalEncoder — scikit-learn 1.5.2 documentation
Encode categorical features as an integer array. The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are converted to ordinal integers.
🌐
Medium
medium.com › @WojtekFulmyk › ordinal-encoding-a-brief-explanation-a29cf374dbc1
Ordinal Encoding — A Brief Explanation | by Wojtek Fulmyk, Data Scientist | Medium
August 3, 2023 - Ordinal encoding maps categorical data to integers preserving order, useful for machine learning models requiring numeric input.
🌐
Kaggle
kaggle.com › code › kiranvairagade › ordinal-encoder
Ordinal Encoder
July 25, 2022 - Python · train_test_splitOrdinalEncoder · This Notebook has been released under the Apache 2.0 open source license. Input1 file · arrow_right_alt · Output0 files · arrow_right_alt · Logs23.9 second run - successful · arrow_right_alt · Comments0 comments ·
🌐
TutorialsPoint
tutorialspoint.com › guided-ordinal-encoding-techniques
Guided Ordinal Encoding Techniques
Ordinal encoding, which turns each label into an integer value and depicts the sequence of labels in the encoded data, is employed when the variables in the data are ordinal. Below is an illustration of how to do this in Python.