Firstly, when you want to encode categorical variables, which is not ordinal (meaning: there is no inherent ordering between the values of the variable/column. ex- cat, dog), you must use one hot encoding.

import pandas as pd
from sklearn.preprocessing import OneHotEncoder 

df = pd.DataFrame({'pets': ['cat', 'dog', 'cat', 'monkey', 'dog', 'meo'], 
                   'owner': ['Champ', 'Ron', 'Brick', 'Champ', 'Veronica', 'Ron'], 
                   'location': ['San_Diego', 'New_York', 'New_York', 'San_Diego', 'San_Diego', 
             'New_York']})

enc = [['cat','dog','monkey'],
       ['Brick', 'Champ', 'Ron', 'Veronica'],
       ['New_York', 'San_Diego']]
ohe = OneHotEncoder(categories=enc, handle_unknown='ignore', sparse=False)

Here, I have modified your enc in a way that can be fed into the OneHotEncoder.

Now comes the point of how can we going to handle the unseen labels?

when you handle_unknown as False, the unseen values will have zeros in all the dummy variables, which in a way would help the model to understand its a unknown value.

colnames= ['{}_{}'.format(col,val) for col,unique_values in zip(df.columns,ohe.categories_) \
                                       for val in unique_values]
pd.DataFrame(ohe.fit_transform(df), columns=colnames) 

Update:

If you are fine with ordinal endocing, the following change could help.


df2.apply(lambda row: [transform_dict[val].get(col,0) \
                                    for val,col in row.items()], 
          axis=1,
          result_type='expand')

#1000 loops, best of 3: 1.17 ms per loop
Answer from Venkatachalam on Stack Overflow
🌐
CodeSignal
codesignal.com › learn › courses › cleaning-and-transforming-data-with-pandas › lessons › encoding-categorical-variables-using-python
Encoding Categorical Variables Using Python
Encoding using map: We use the map method to replace each label in the Gender column based on our specified dictionary: {'Male': 1, 'Female': 0}. This dictionary tells Python to encode Male as 1 and Female as 0. Adding a new column: The new column Gender_Encoded is created and added to the DataFrame. This column contains the numerical representation of the Gender column, which can now be used for further analysis or as input into a machine learning algorithm. In this lesson, we explored the importance and different methods of encoding categorical variables, with a specific focus on using dictionary mapping in Python.
Discussions

pandas - How to encode one or multiple categorical variables into one feature - Stack Overflow
I am trying to train a machine learning model on some categorical data I have, however I am unsure how to encode it. If I have a table like the following, what is the best way to encode "var_3... More on stackoverflow.com
🌐 stackoverflow.com
python - How to encode when u have multiple categories in a column - Stack Overflow
My data frame looks like this Pandas data frame with multiple categorical variables for a user I made sure there are no duplicates in it. I want to encode it and I want my final output like this I... More on stackoverflow.com
🌐 stackoverflow.com
machine learning - Strategies to encode categorical variables with many categories - Data Science Stack Exchange
I was going over the Kaggle competitions IEEE,Categorical Feature Encoding Challenge and one of the ways in which categorical variables have been handled is by replacing the variables by the respec... More on datascience.stackexchange.com
🌐 datascience.stackexchange.com
December 9, 2019
python - Encode categorical data - Stack Overflow
12 How to encode a categorical variable in sklearn? More on stackoverflow.com
🌐 stackoverflow.com
March 12, 2019
🌐
Practical Business Python
pbpython.com › categorical-encoding.html
Guide to Encoding Categorical Values in Python - Practical Business Python
make object fuel_type object aspiration object num_doors int64 body_style category drive_wheels object engine_location object engine_type object num_cylinders int64 fuel_system object dtype: object · Then you can assign the encoded variable to a new column using the cat.codes accessor:
🌐
Train in Data
blog.trainindata.com › one-hot-encoding-categorical-variables
One-hot encoding categorical variables | Train in Data Blog
January 25, 2023 - Hence, one-hot encoding of variables ... with multiple categorical features can expand the feature space dramatically. To reduce the number of binary variables, we can perform one-hot encoding of the most frequent categories only. One-hot encoding of top categories is equivalent to treating the less frequent categories as a single, unique category. Let’s implement one-hot encoding of the most popular categories using pandas and Feature-engine. Let’s first import the necessary Python libraries ...
🌐
Analytics Vidhya
analyticsvidhya.com › home › what are categorical data encoding methods | binary encoding
What are Categorical Data Encoding Methods | Binary Encoding
May 1, 2025 - By understanding the nature of ... and utilized by their models. For encoding categorical data, we have a python package category encoders....
🌐
Analytics Vidhya
analyticsvidhya.com › home › how to perform one-hot encoding for multi categorical variables
How to Perform One-Hot Encoding For Multi Categorical Variables
February 3, 2025 - The technique is that we will limit one-hot encoding to the 10 most frequent labels of the variable. This means that we would make one binary variable for each of the 10 most frequent labels only, this is equivalent to grouping all other labels ...
Find elsewhere
🌐
Medium
medium.com › @jaberi.mohamedhabib › encoding-categorical-variables-methods-and-techniques-in-pandas-scikit-learn-and-using-dummy-216ae2d5128d
Encoding Categorical Variables: Methods and Techniques in Pandas, Scikit-learn, and Using Dummy Function | by JABERI Mohamed Habib | Medium
September 27, 2024 - One-Hot Encoding converts each unique category into a new column (binary vector), with each row marked as 1 in the column corresponding to the category it belongs to and 0 in all other columns. This is suitable for nominal categorical variables.
🌐
Medium
medium.com › dwadda › ways-of-encoding-categorical-variables-b7a798931c8c
Ways of encoding categorical variables | by Sejal Chandra | SejalChandra | Medium
April 8, 2020 - If we apply one-hot encoding to the feature having multiple categories(let’s say 100), then creating 99 more columns leads to “curse of dimensionality.” In the example below, the variable “state” has 4 different categories.
🌐
Scikit-learn course
inria.github.io › scikit-learn-mooc › python_scripts › 03_categorical_pipeline.html
Encoding of categorical variables — Scikit-learn course
One-hot encoding categorical variables with high cardinality can cause computational inefficiency in tree-based models. Because of this, it is not recommended to use OneHotEncoder in such cases even if the original categories do not have a given order.
🌐
GeeksforGeeks
geeksforgeeks.org › machine learning › encoding-categorical-data-in-sklearn
Encoding Categorical Data in Sklearn - GeeksforGeeks
September 17, 2025 - Always use the same encoder objects on train and test data to ensure consistency. For categorical variable exploration and encoding in a deployed or production ML pipeline, prefer maintaining category order explicitly for any ordinal features.
🌐
Kaggle
kaggle.com › code › paulrohan2020 › tutorial-encoding-categorical-variables
Tutorial-Encoding-Categorical-Variables | Kaggle
April 19, 2022 - Explore and run AI code with Kaggle Notebooks | Using data from Breast cancer data
🌐
Medium
medium.com › @favourphilic › simple-guide-to-encoding-categorical-data-in-python-6fa517150350
Simple guide to encoding categorical data in python. | by Victor Jokanola | Medium
June 21, 2022 - As mentioned earlier, category encoders allow us to specify desired columns needed for transformation. In this example, we will be transforming all the feature vectors using Ordinal encoder. This attribute is important as it allows selection of a dataframe subset in a situation where we have several variables of different types.
🌐
Kaggle
kaggle.com › code › adepvenugopal › categorical-columns-encoding-methods
Categorical columns encoding methods
September 18, 2022 - OverviewIntroductionCategorical Data EncodingTable of contentLabel Encoding or Ordinal EncodingOne-Hot EncodingDummy EncodingEffect EncodingHash EncodingBinary EncodingBase N EncodingTarget EncodingEndnote
🌐
MachineLearningMastery
machinelearningmastery.com › home › blog › 3 ways to encode categorical variables for deep learning
3 Ways to Encode Categorical Variables for Deep Learning - MachineLearningMastery.com
August 26, 2020 - This means that if your data contains categorical data, you must encode it to numbers before you can fit and evaluate a model. The two most popular techniques are an integer encoding and a one hot encoding, although a newer technique…
Top answer
1 of 1
4

Generally, the logic of the categorical count transformation lies in the fact that features with similar frequencies tend to behave similarly. Have words in a corpus as an example, common words share little or no real information whereas uncommon words share more information with an algorithm.

Specifically, certain algorithms (tree-based methods) could even yield rules given an unspecified category from an event count. Say, for example, we have an unknown category whose count is 4. The algorithm may give a rule:

If Column Count is < 5 and N is > 3 = X

That will be exactly the same as if an algorithm took a One-Hot encoded column and gave a rule:

If One-Hot-Encoded-Column is > 0 = X

In that case, a tree-based algorithm will make several rules from many categories using the same count column. But how I said at the beginning, algorithms generalize among populations of similar counts so most likely you will find rules like:

If Column Counts is < 10 and N is > 3 = X

Which will often contain different categories that behave similarly. Just check the models and look for parameters/ importance of the column in question to see this for yourself.

Secondly, I was wondering if anyone may be willing to share other techniques of dealing with categorical variables.

Feature hashing became really popular there not so long ago. Hashing has very nice properties and it's a whole topic learned at schools but the main principle is that if you have a category with high cardinality you decide a minimum number of reduced categories (hashes) that all the categories will have to share. if two categories share the same hash or bucket, that is called a hash collision. Feature hashing doesn't deal with hash collisions because according to some authors (I don't have the reference here) may improve accuracy by forcing the algorithm to pick more carefully the features.

There are many ways we can encode these categorical variables as numbers and use them in the algorithm.

1) One Hot Encoding
2) Label Encoding
3) Ordinal Encoding
4) Helmert Encoding
5) Binary Encoding
6) Frequency Encoding
7) Mean Encoding
8) Weight of Evidence Encoding
9) Probability Ratio Encoding
10) Hashing Encoding
11) Backward Difference Encoding
12) Leave One Out Encoding
13) James-Stein Encoding
14) M-estimator Encoding

Find the below cheatsheet

More Info

🌐
Stack Overflow
stackoverflow.com › questions › 55120637 › encode-categorical-data
python - Encode categorical data - Stack Overflow
March 12, 2019 - from sklearn.preprocessing import LabelEncoder,OneHotEncoder Data = pd.DataFrame({'Company_share_code' : ['A', 'B', 'C', 'B', 'B', 'A']}) labelencoder=LabelEncoder() Data['Company_share_code']=labelencoder.fit_transform(Data['Company_share_code']) #One hot encoding Onehotencoder=OneHotEncoder(categorical_features=[0]) h = Onehotencoder.fit_transform(Data['Company_share_code'].values.reshape(-1, 1)) h.todense() # Output matrix([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.], [0., 1., 0.], [0., 1., 0.], [1., 0., 0.]])
🌐
Towards Data Science
towardsdatascience.com › home › artificial intelligence › all about categorical variable encoding
All about Categorical Variable Encoding | Towards Data Science
February 4, 2023 - 1) One Hot Encoding 2) Label Encoding 3) Ordinal Encoding 4) Helmert Encoding 5) Binary Encoding 6) Frequency Encoding 7) Mean Encoding 8) Weight of Evidence Encoding 9) Probability Ratio Encoding 10) Hashing Encoding 11) Backward Difference Encoding 12) Leave One Out Encoding 13) James-Stein Encoding 14) M-estimator Encoding (updated) ... For explanation, I will use this data frame, which has two independent variables or features(Temperature and Color) and one label (Target). It also has Rec-No, which is a sequence number of the record. There is a total of 10 records in this data frame. Python code would look as below. ... We will use Pandas and Scikit-learn and category_encoders (Scikit-learn contribution library) to show different encoding methods in Python.
🌐
YouTube
youtube.com › watch
Encoding Categorical Data | Machine Learning Fundamentals - YouTube
In this video, I teach you how to encode categorical data for Machine Learning. This includes both nominal and ordinal categorical data with ordinal encoding...
Published: July 16, 2024