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
In the following example, “a” and “d” are considered infrequent and grouped together into a single category, “b” and “c” are their own categories, unknown values are encoded as 3 and missing values are encoded as 4. >>> X_train = np....
🌐
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 ·
🌐
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.
🌐
ProgramCreek
programcreek.com › python › example › 112363 › sklearn.preprocessing.OrdinalEncoder
Python Examples of sklearn.preprocessing.OrdinalEncoder
def test_ordinal_encoder_onecat(self): data = [["cat"], ["cat"]] model = OrdinalEncoder(categories="auto") model.fit(data) inputs = [("input1", StringTensorType([None, 1]))] model_onnx = convert_sklearn(model, "ordinal encoder one string cat", inputs) self.assertTrue(model_onnx is not None) dump_data_and_model( data, model, model_onnx, basename="SklearnOrdinalEncoderOneStringCat", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.5.0')", )
🌐
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.
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

🌐
scikit-learn
scikit-learn.org › 0.20 › modules › generated › sklearn.preprocessing.OrdinalEncoder.html
sklearn.preprocessing.OrdinalEncoder — scikit-learn 0.20.4 documentation
>>> from sklearn.preprocessing import OrdinalEncoder >>> enc = OrdinalEncoder() >>> X = [['Male', 1], ['Female', 3], ['Female', 2]] >>> enc.fit(X) ...
🌐
Trainindata
feature-engine.trainindata.com › en › 1.8.x › user_guide › encoding › OrdinalEncoder.html
Ordinal Encoding — 1.8.3
If the encoding_method is defined as “arbitrary”, then OrdinalEncoder() will assign numeric values to the categorical variable on a first-come first-served basis i.e., in the order the categories are encountered in the dataset.
Find elsewhere
🌐
Educative
educative.io › answers › ordinal-encoding-in-python
Ordinal encoding in Python
To execute ordinal encoding in Python, the following steps are typically followed. The first step is to install the scikit-learn library to use the OrdinalEncoder package as follows:
🌐
KoalaTea site
koalatea.io › python-ordinal-encoding
Ordinal Encoding in Python - KoalaTea
December 14, 2023 - import category_encoders mapping = [ { 'col': 'shirts', 'mapping':{ 'small': 0, 'medium': 1, 'large': 2, } } ] encoder = category_encoders.OrdinalEncoder( cols = ['shirts'], return_df = True, mapping = mapping ) encoder.fit_transform(df['shirts']) c:\users\krh12\appdata\local\programs\python\python38\lib\site-packages\category_encoders\utils.py:21: FutureWarning: is_categorical is deprecated and will be removed in a future version.
🌐
Codefinity
codefinity.com › courses › v2 › a65bbc96-309e-4df9-a790-a1eb8c815a1c › 1fce4aa9-710f-4bc9-ad66-16b4b2d30929 › 3ece2d64-2c58-452c-b843-725391f29bd4
Learn OrdinalEncoder | Preprocessing Data with Scikit-learn
encoder = OrdinalEncoder(categories=[col1_categories, col2_categories, ...]) ... Thanks for your feedback! Section 2. Chapter 5 ... The next issue to address is categorical data. There are two main types of categorical variables. Ordinal data has a natural order, while nominal data does not. Because of this order, categories can be encoded as numbers according to their ranking. For example, a 'rate' column with the values 'Terrible', 'Bad', 'OK', 'Good', and 'Great' ...
🌐
Medium
medium.com › @paghadalsneh › encoding-categorical-data-ordinal-encoding-86f91fd07fcf
Encoding Categorical Data | Ordinal Encoding | by Sneh Paghdal | Medium
January 23, 2025 - # Load dataset df = pd.read_csv('customer.csv')# Select relevant columns df = df.iloc[:, 2:]# Initialize OrdinalEncoder with specific category order oe = OrdinalEncoder(categories=[['Poor', 'Average', 'Good'], ['School', 'UG', 'PG']])# Fit and transform the data X_train = oe.fit_transform(df[['review', 'education']])print(X_train)
🌐
PythonProg
pythonprog.com › home › scikit-learn’s preprocessing.ordinalencoder in python (with examples)
Scikit-Learn's preprocessing.OrdinalEncoder in Python (with Examples) | PythonProg
February 8, 2024 - The Scikit-Learn OrdinalEncoder is a valuable tool for converting ordinal categorical data into numerical values that retain the order information. By understanding how to use it effectively, data scientists can enhance the quality of their machine learning models when dealing with ordinal features. Scikit-Learn’s preprocessing.MaxAbsScaler in Python (with Examples)
🌐
scikit-learn
scikit-learn.org › 0.22 › modules › generated › sklearn.preprocessing.OrdinalEncoder.html
sklearn.preprocessing.OrdinalEncoder — scikit-learn 0.22.2 documentation
>>> from sklearn.preprocessing import OrdinalEncoder >>> enc = OrdinalEncoder() >>> X = [['Male', 1], ['Female', 3], ['Female', 2]] >>> enc.fit(X) OrdinalEncoder() >>> enc.categories_ [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] >>> enc.transform([['Female', 3], ['Male', 1]]) array([[0., 2.], [1., 0.]])
🌐
Trainindata
feature-engine.trainindata.com › en › latest › user_guide › encoding › OrdinalEncoder.html
Ordinal Encoding — 1.9.4 - Feature-engine
If the encoding_method is defined as “arbitrary”, then OrdinalEncoder() will assign numeric values to the categorical variable on a first-come first-served basis i.e., in the order the categories are encountered in the dataset.
🌐
Towards Data Science
towardsdatascience.com › home › latest › feature engineering ordinal variables
Feature Engineering Ordinal Variables | Towards Data Science
January 16, 2025 - # Pass in the correctly-ordered sequence into Ordinal Encoder ordinal_encoder = OrdinalEncoder(categories=[g,r]) X_ExT2 = ordinal_encoder.fit_transform(X_ex)
🌐
Applied AI Blog
appliedaicourse.com › home › data science › ordinal encoding — a brief guide
Ordinal Encoding — A Brief Guide
April 28, 2025 - import pandas as pd from sklearn.preprocessing import OrdinalEncoder # Load the Titanic dataset url = 'https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv' titanic_df = pd.read_csv(url) # Select the 'Pclass' feature (Passenger Class: 1 = First, 2 = Second, 3 = Third) print(titanic_df['Pclass'].value_counts()) # Although already numerical, Pclass represents an ordinal category (higher class = higher value) encoder = OrdinalEncoder() # Apply encoder titanic_df['Pclass_encoded'] = encoder.fit_transform(titanic_df[['Pclass']]) # Visualize before and after print(titanic_df[['Pclass', 'Pclass_encoded']].head()) In this example, the ‘Pclass’ feature, representing passenger class ranking, is treated as an ordinal variable.
Top answer
1 of 1
16

I'm not sure if you ever figured this out but I was trying to find answers on this exact same question and there aren't really any good answers in my opinion. I finally figured it out though. OrdinalEncoder is capable of encoding multiple columns in a dataframe. So, when you instantiate OrdinalEncoder(), you give the categories parameter a list of lists:

enc = OrdinalEncoder(categories=[list_of_values_cat1, list_of_values_cat2, etc])

Specifically, in your example above, you would just put ['low', 'med', 'high'] inside another list:

end = OrdinalEncoder(categories=[['low', 'med', 'high']])
enc.fit_transform(X.loc[:,['animals']])
>>array([[0.],
         [1.],
         [0.],
         [2.],
         [0.],
         [2.]])
# Now 'low' is correctly mapped to 0, 'med' to 1, and 'high' to 2

To see how you can encode multiple columns with their own individual ordinal values, try this:

# Sample dataframe with 2 ordinal categorical columns: 'temp' and 'place'
categorical_df = pd.DataFrame({'my_id': ['101', '102', '103', '104'],
                               'temp': ['hot', 'warm', 'cool', 'cold'], 
                               'place': ['third', 'second', 'first', 'second']})

# In the 'temp' column, I want 'cold' to be 0, 'cool' to be 1, 'warm' to be 2, and 'hot' to be 3
# In the 'place' column, I want 'first' to be 0, 'second' to be 1, and 'third' to be 2
temp_categories = ['cold', 'cool', 'warm', 'hot']
place_categories = ['first', 'second', 'third']

# Now, when you instantiate the encoder, both of these lists go in one big categories list:
encoder = OrdinalEncoder(categories=[temp_categories, place_categories])

encoder.fit_transform(categorical_df[['temp', 'place']])
>>array([[3., 2.],
         [2., 1.],
         [1., 0.],
         [0., 1.]])
🌐
Medium
medium.com › @WojtekFulmyk › ordinal-encoding-a-brief-explanation-a29cf374dbc1
Ordinal Encoding — A Brief Explanation | by Wojtek Fulmyk, Data Scientist | Medium
August 3, 2023 - import numpy as np from sklearn.preprocessing import OrdinalEncoder encoder = OrdinalEncoder() sizes = ["small", "medium", "large"] # reshape to 2D array sizes = np.array(sizes).reshape(-1,1) encoded = encoder.fit_transform(sizes) print(encoded)
🌐
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 - We will explore ordinal encoding in-depth and how it can be leveraged when implementing a Decision Tree Regressor. Through practical Python examples using the OrdinalEncoder from sklearn and the Ames Housing dataset, this guide will provide you with the skills to implement these strategies ...