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.array( ... [["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3 + [np.nan]], ... dtype=object).T >>> enc = OrdinalEncoder( ... handle_unknown="use_encoded_value", unknown_value=3, ...
๐ŸŒ
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 - Here we will create a maplist that will be passed into the mapping parameter to tell the encoder which values will be associated with which number, and then instantiate an OrdinalEncoder object while passing in the aforementioned maplist into our mapping parameter: from category_encoders import OrdinalEncoder maplist = [{'col': 'satisfaction_rating', 'mapping': {'Very Dissatisfied': 0, 'Dissatisfied': 1,'Neutral': 2, 'Satisfied': 3, 'Very Satisfied': 4}}]oe = OrdinalEncoder(mapping=maplist) WARNING: If you do not use mapping=, the encoder will not know how to order your values and the encoder will pick random integers for you, and your data will most likely not be in order.
๐ŸŒ
Trainindata
feature-engine.trainindata.com โ€บ en โ€บ latest โ€บ user_guide โ€บ encoding โ€บ OrdinalEncoder.html
Ordinal Encoding โ€” 1.9.4 - Feature-engine
When encountering unseen categories, OrdinalEncoder() has the option to raise an error and fail, ignore the rare category, in which case it will be encoded as np.nan, or encode it into -1. You can define this behaviour through the unseen parameter. In the rest of the page, weโ€™ll show different ways how we can use ...
๐ŸŒ
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 - We will first split the dataset, then prepare the encoding on the training set, and apply it to the test set. We can then fit the OrdinalEncoder on the training dataset and use it to transform the train and test datasets.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ machine learning โ€บ how-to-perform-ordinal-encoding-using-sklearn
How to Perform Ordinal Encoding Using Sklearn - GeeksforGeeks
August 5, 2025 - It is used in machine learning as various algorithms work best with numerical data only. Let's see the implementation of Ordinal Encoding using Sklearn with the help of examples, ... Sets up a sample dataset with students and their grades. Converts the data into a pandas DataFrame. ... data = { 'Student': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'], 'Grade': ['A', 'B', 'C', 'A', 'B'] } df = pd.DataFrame(data) print(df) ... Initializes OrdinalEncoder and explicitly sets the order: 'A' < 'B' < 'C'.
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

๐ŸŒ
YouTube
youtube.com โ€บ watch
Using Ordinal Encoder for encoding input categorical features | Machine Learning - YouTube
In this tutorial, we'll go over ordinal encoding using scikit-learn's OrdinalEncoder class.Ordinal Encoding is useful when there is an inherent 'order' betwe...
Published: July 12, 2020
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.]])
Find elsewhere
๐ŸŒ
Trainindata
feature-engine.trainindata.com โ€บ en โ€บ 1.8.x โ€บ user_guide โ€บ encoding โ€บ OrdinalEncoder.html
Ordinal Encoding โ€” 1.8.3
When encountering unseen categories, OrdinalEncoder() has the option to raise an error and fail, ignore the rare category, in which case it will be encoded as np.nan, or encode it into -1. You can define this behaviour through the unseen parameter. In the rest of the page, weโ€™ll show different ways how we can use ...
๐ŸŒ
scikit-learn
scikit-learn.org โ€บ dev โ€บ modules โ€บ generated โ€บ sklearn.preprocessing.OrdinalEncoder.html
OrdinalEncoder โ€” scikit-learn 1.10.dev0 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.array( ... [["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3 + [np.nan]], ... dtype=object).T >>> enc = OrdinalEncoder( ... handle_unknown="use_encoded_value", unknown_value=3, ...
๐ŸŒ
scikit-learn
scikit-learn.org โ€บ 0.20 โ€บ modules โ€บ generated โ€บ sklearn.preprocessing.OrdinalEncoder.html
sklearn.preprocessing.OrdinalEncoder โ€” scikit-learn 0.20.4 documentation
... Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to an ordinal encoding. >>> from sklearn.preprocessing import OrdinalEncoder >>> enc = OrdinalEncoder() >>> X = [['Male', 1], ['Female', 3], ['Female', 2]] >>> enc.fit(X) ...
๐ŸŒ
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)
๐ŸŒ
scikit-learn
scikit-learn.org โ€บ 1.0 โ€บ modules โ€บ generated โ€บ sklearn.preprocessing.OrdinalEncoder.html
sklearn.preprocessing.OrdinalEncoder โ€” scikit-learn 1.0.2 documentation
Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to an ordinal encoding. >>> from sklearn.preprocessing import OrdinalEncoder >>> enc = OrdinalEncoder() >>> X = [['Male', 1], ['Female', ...
๐ŸŒ
Trainindata
feature-engine.trainindata.com โ€บ en โ€บ 1.7.x โ€บ user_guide โ€บ encoding โ€บ OrdinalEncoder.html
OrdinalEncoder โ€” 1.7.0
encoder = OrdinalEncoder( encoding_method='ordered', variables=['pclass', 'cabin', 'embarked'], ignore_format=True) encoder.fit(X_train, y_train) With fit() the encoder learns the mappings for each category, which are stored in its encoder_dict_ parameter: ... In the encoder_dict_ we find the integers that will replace each one of the categories of each variable that we want to encode.
๐ŸŒ
Thomasjpfan
thomasjpfan.github.io โ€บ scikit-learn-website โ€บ modules โ€บ generated โ€บ sklearn.preprocessing.OrdinalEncoder.html
sklearn.preprocessing.OrdinalEncoder โ€” scikit-learn 0.22.dev0 documentation
... The categories of each feature determined during fitting (in order of the features in X and corresponding with the output of transform). ... Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to an ordinal encoding.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ ordinal-encoding-in-python
Ordinal encoding in Python
In this step, we pass the Colors column to the fit_transform function to perform ordinal encoding, as shown below: df['Colors_Encoded'] = encoder.fit_transform(df[['Colors']]) Note: The OrdinalEncoder package can encode multiple columns simultaneously. The following code shows how we can use the OrdinalEncoder package in Python:
๐ŸŒ
Codepointtech
codepointtech.com โ€บ home โ€บ mastering ordinal encoding: a guide to sklearnโ€™s ordinalencoder
Mastering Ordinal Encoding: A Guide to Sklearn's OrdinalEncoder - codepointtech.com
July 4, 2026 - import numpy as np # Create a new DataFrame with an unknown category new_data = { "ID": [7], "Education": ["Postdoc"], # "Postdoc" is an unknown category "Satisfaction": ["Excellent"] } df_new = pd.DataFrame(new_data) # Re-initialize the encoder with handle_unknown parameter encoder_with_unknown = OrdinalEncoder( categories=categories_list, handle_unknown="use_encoded_value", unknown_value=-1 # Assign -1 to unknown categories ) # Fit on original data, then transform new data encoder_with_unknown.fit(df[columns_to_encode]) df_new[columns_to_encode] = encoder_with_unknown.transform(df_new[columns_to_encode]) print("\nDataFrame with unknown category handled:") print(df_new)
๐ŸŒ
Scikit-learn
contrib.scikit-learn.org โ€บ category_encoders โ€บ ordinal.html
Ordinal โ€” Category Encoders 2.11.1 documentation
set_transform_request(*, override_return_df: bool | None | str = '$UNCHANGED$') โ†’ OrdinalEncoder๏ƒ ยท Configure whether metadata should be requested to be passed to the transform method. Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()).
๐ŸŒ
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 - To implement ordinal encoding in Python, we use the OrdinalEncoder from sklearn.preprocessing. This tool is particularly useful for preparing ordinal features for tree-based models. It allows us to specify the order of categories manually, ensuring that the encoding respects the natural hierarchy of the data.