Approach 1: You can use pandas' pd.get_dummies.

Example 1:

import pandas as pd
s = pd.Series(list('abca'))
pd.get_dummies(s)
Out[]: 
     a    b    c
0  1.0  0.0  0.0
1  0.0  1.0  0.0
2  0.0  0.0  1.0
3  1.0  0.0  0.0

Example 2:

The following will transform a given column into one hot. Use prefix to have multiple dummies.

import pandas as pd
        
df = pd.DataFrame({
          'A':['a','b','a'],
          'B':['b','a','c']
        })
df
Out[]: 
   A  B
0  a  b
1  b  a
2  a  c

# Get one hot encoding of columns B
one_hot = pd.get_dummies(df['B'])
# Drop column B as it is now encoded
df = df.drop('B',axis = 1)
# Join the encoded df
df = df.join(one_hot)
df  
Out[]: 
       A  a  b  c
    0  a  0  1  0
    1  b  1  0  0
    2  a  0  0  1

Approach 2: Use Scikit-learn

Using a OneHotEncoder has the advantage of being able to fit on some training data and then transform on some other data using the same instance. We also have handle_unknown to further control what the encoder does with unseen data.

Given a dataset with three features and four samples, we let the encoder find the maximum value per feature and transform the data to a binary one-hot encoding.

>>> from sklearn.preprocessing import OneHotEncoder
>>> enc = OneHotEncoder()
>>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])   
OneHotEncoder(categorical_features='all', dtype=<class 'numpy.float64'>,
   handle_unknown='error', n_values='auto', sparse=True)
>>> enc.n_values_
array([2, 3, 4])
>>> enc.feature_indices_
array([0, 2, 5, 9], dtype=int32)
>>> enc.transform([[0, 1, 1]]).toarray()
array([[ 1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  0.]])

Here is the link for this example: http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html

Answer from Sayali Sonawane on Stack Overflow
🌐
scikit-learn
scikit-learn.org › stable › modules › generated › sklearn.preprocessing.OneHotEncoder.html
OneHotEncoder — scikit-learn 1.9.1 documentation
Encodes categorical features using the target. ... Performs a one-hot encoding of dictionary items (also handles string-valued features).
🌐
GeeksforGeeks
geeksforgeeks.org › machine learning › ml-one-hot-encoding
One Hot Encoding in Machine Learning - GeeksforGeeks
One-Hot Encoding can be implemented in Python using libraries such as Pandas and Scikit-learn, which provide simple and efficient methods for converting categorical data into binary columns.
Published: May 29, 2026
Discussions

Pandas factorize and one hot encoding
Say you use factorize and then apply k means clustering. The algorithm will assume the 1 is closer to 2 than to 10. Does that make sense? If factorize just converts text to numbers, is there any reason to believe that the order has some meaning? With one hot encoding theres no such assumption. Each possible value is a boolean, they're all equally close to each other. So, it depends heavily on what you're doing with the data, but one hot encoding is usually safer. More on reddit.com
🌐 r/learnmachinelearning
8
10
June 1, 2024
What alternatives are there to one hot encoding?
There's something called Target Encoding which I've found to be quite effective. It is basically where you use the target variable itself to inform the encoding of the category. For instance, let's say you're doing the classic home price problem where you're trying to predict a home's value. You've got home style as an input (Crafstman, Modern, etc.). You would order the home styles by their average (or perhaps median) home price for that style and use that as the numeric encoding in your model. It's tricky to get quite right, because there can be high variability (especially among rarer home types, in this example). So you can have a cut-off that says "for instances where there's less than X examples in the training set, use the average/min/max/whatever." You can also remove some variability by doing some k-folding. Just realized as I'm typing this, that articles have been written. so why am I typing this out? https://medium.com/@pouryaayria/k-fold-target-encoding-dfe9a594874b -- not sure if this is the best article, but on a quick skim seems fine. One thing to consider is to try multiple methods at once, like create a frequency-encoded and a target-encoded version of the same feature. They may convey different information. More on reddit.com
🌐 r/datascience
12
6
October 6, 2022
How can I decode one hot vector? (and when can we use it?)
np.argmax(one_hot, axis=1) More on reddit.com
🌐 r/MachineLearning
2
0
September 12, 2016
What is the difference between applying One Hot Encoding to a categorical column and changing the data type to categorical (in pandas)?
To the best of my understanding, the regressor can't read strings, so the string "32" instead of the number 32 cannot be parsed and would result in an error.If you get the 'dummies' you convert each label into a column filled with ones (1) and zeros (0). These numeric values can then be fed into a regressor. As an aside, the regressor doesn't "recognise" the labels (as strings) but it can deal with the distance between the transformed columns for two (or more) different labels and use that as a differentiation in the regression. More on reddit.com
🌐 r/learnmachinelearning
6
2
January 28, 2022
Top answer
1 of 16
317

Approach 1: You can use pandas' pd.get_dummies.

Example 1:

import pandas as pd
s = pd.Series(list('abca'))
pd.get_dummies(s)
Out[]: 
     a    b    c
0  1.0  0.0  0.0
1  0.0  1.0  0.0
2  0.0  0.0  1.0
3  1.0  0.0  0.0

Example 2:

The following will transform a given column into one hot. Use prefix to have multiple dummies.

import pandas as pd
        
df = pd.DataFrame({
          'A':['a','b','a'],
          'B':['b','a','c']
        })
df
Out[]: 
   A  B
0  a  b
1  b  a
2  a  c

# Get one hot encoding of columns B
one_hot = pd.get_dummies(df['B'])
# Drop column B as it is now encoded
df = df.drop('B',axis = 1)
# Join the encoded df
df = df.join(one_hot)
df  
Out[]: 
       A  a  b  c
    0  a  0  1  0
    1  b  1  0  0
    2  a  0  0  1

Approach 2: Use Scikit-learn

Using a OneHotEncoder has the advantage of being able to fit on some training data and then transform on some other data using the same instance. We also have handle_unknown to further control what the encoder does with unseen data.

Given a dataset with three features and four samples, we let the encoder find the maximum value per feature and transform the data to a binary one-hot encoding.

>>> from sklearn.preprocessing import OneHotEncoder
>>> enc = OneHotEncoder()
>>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])   
OneHotEncoder(categorical_features='all', dtype=<class 'numpy.float64'>,
   handle_unknown='error', n_values='auto', sparse=True)
>>> enc.n_values_
array([2, 3, 4])
>>> enc.feature_indices_
array([0, 2, 5, 9], dtype=int32)
>>> enc.transform([[0, 1, 1]]).toarray()
array([[ 1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  0.]])

Here is the link for this example: http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html

2 of 16
149

Much easier to use Pandas for basic one-hot encoding. If you're looking for more options you can use scikit-learn.

For basic one-hot encoding with Pandas you pass your data frame into the get_dummies function.

For example, if I have a dataframe called imdb_movies:

...and I want to one-hot encode the Rated column, I do this:

pd.get_dummies(imdb_movies.Rated)

This returns a new dataframe with a column for every "level" of rating that exists, along with either a 1 or 0 specifying the presence of that rating for a given observation.

Usually, we want this to be part of the original dataframe. In this case, we attach our new dummy coded frame onto the original frame using "column-binding.

We can column-bind by using Pandas concat function:

rated_dummies = pd.get_dummies(imdb_movies.Rated)
pd.concat([imdb_movies, rated_dummies], axis=1)

We can now run an analysis on our full dataframe.

SIMPLE UTILITY FUNCTION

I would recommend making yourself a utility function to do this quickly:

def encode_and_bind(original_dataframe, feature_to_encode):
    dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])
    res = pd.concat([original_dataframe, dummies], axis=1)
    return(res)

Usage:

encode_and_bind(imdb_movies, 'Rated')

Result:

Also, as per @pmalbu comment, if you would like the function to remove the original feature_to_encode then use this version:

def encode_and_bind(original_dataframe, feature_to_encode):
    dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])
    res = pd.concat([original_dataframe, dummies], axis=1)
    res = res.drop([feature_to_encode], axis=1)
    return(res) 

You can encode multiple features at the same time as follows:

features_to_encode = ['feature_1', 'feature_2', 'feature_3',
                      'feature_4']
for feature in features_to_encode:
    res = encode_and_bind(train_set, feature)
🌐
Medium
medium.com › @michaeldelsole › what-is-one-hot-encoding-and-how-to-do-it-f0ae272f1179
What is One Hot Encoding and How to Do It | by Michael DelSole | Medium
April 24, 2018 - Now let’s do the actual encoding. Sklearn makes it incredibly easy, but there is a catch. You might have noticed we imported both the labelencoder and the one hot encoder. Sklearn’s one hot encoder doesn’t actually know how to convert categories to numbers, it only knows how to convert numbers to binary.
🌐
DataCamp
datacamp.com › tutorial › one-hot-encoding-python-tutorial
What Is One Hot Encoding and How to Implement It in Python | DataCamp
June 26, 2024 - In this article, we’ll explore the concept of one-hot encoding, its benefits, and its practical implementation in Python using libraries such as Pandas and Scikit-learn.
🌐
Codecademy
codecademy.com › article › what-is-one-hot-encoding-and-how-to-implement-it-in-python
What is One Hot Encoding and How to Implement it in Python? | Codecademy
We can also perform one-hot encoding on multiple columns at once using the get_dummies() function in Python. For this, we need to pass all the column names we want to encode in a list to the columns parameter.
Find elsewhere
🌐
Train in Data
blog.trainindata.com › one-hot-encoding-categorical-variables
One-hot encoding categorical variables | Train in Data Blog
January 25, 2023 - Let’s implement one-hot encoding of the most popular categories using pandas and Feature-engine. Let’s first import the necessary Python libraries and get the dataset ready:
🌐
CodeSignal
codesignal.com › learn › courses › data-cleaning-and-preprocessing-techniques › lessons › categorical-data-encoding-techniques-in-python-an-introduction-to-label-and-one-hot-encoding
An Introduction to Label and One-Hot Encoding
As One-Hot encoding converts each category value into a new column and assigns a 1 or 0 (True/False) value to the column, it does not impose any ordinal relationship among categories where there is none. This can often be the case with labels like 'Red', 'Blue', 'Green'.
🌐
Medium
medium.com › @creatorvision03 › one-hot-encoding-a-comprehensive-guide-with-python-code-and-examples-for-effective-categorical-2fbbc111c320
“One-Hot Encoding: A Comprehensive Guide with Python Code and Examples for Effective Categorical Data Representation” | by Shivang Gupta | Medium
July 2, 2023 - By converting categorical data into binary vectors, it allows algorithms to effectively process and interpret the information. In this article, we discussed the concept of one-hot encoding, and its benefits, and provided a code example for implementation using Python and scikit-learn.
🌐
Analytics Vidhya
analyticsvidhya.com › home › one hot encoding data in machine learning
One Hot Encoding Data in Machine Learning - Analytics vidhya
March 28, 2025 - A. One-hot encoding is achieved in Python using tools like scikit-learn’s OneHotEncoder or pandas’ get_dummies function.
🌐
Kaggle
kaggle.com › code › marcinrutecki › one-hot-encoding-everything-you-need-to-know
One Hot Encoding - everything you need to know
February 23, 2023 - Python · 1.1 One Hot Encoder vs get_dummies1.2 The dummy variable trap: drop or not to drop?1.3 Possible drawbacks of dropping a column during one hot encoding1.4 Decision tree-based models vs one hot encoding1.5 One Hot Encoding vs very high number of categorical features1.6 Pipelines and One Hot Encoding1.7 One Hot Encoding - before or after train-test split?1.8 Best practices1.9 Simple examples2.1 Import Libraries2.2 Import Data2.3 Data Set Characteristics2.4 Dataset Attributes3.1 Dealin with missing values in TotalCharges3.2 Dealing with duplicated values3.3 Creating numerical and categorical lists4.1 Train test split - stratified splitting4.2 Feature scaling4.3 One hot Encoding4.4 Feature importance ·
🌐
AI Mind
pub.aimind.so › one-hot-encoding-for-machine-learning-with-python-and-scikit-learn-c6d8e1173760
One-Hot Encoding for Machine Learning (with Python and Scikit-Learn) | by Francesco Franco | AI Mind
November 22, 2024 - We can then use Scikit-learn for converting the values into a one-hot encoded array, because it offers the sklearn.preprocessing.OneHotEncoder module. We first import the numpy module for converting a Python list into a NumPy array, and the preprocessing module from Scikit-learn.
🌐
Built In
builtin.com › articles › one-hot-encoding
One Hot Encoding Explained | Built In
February 15, 2024 - If you want to perform one hot encoding, both sklearn.preprocessing.OneHotEncoder and pandas.get_dummies are popular choices.
🌐
YouTube
youtube.com › watch
One Hot Encoder with Python Machine Learning (Scikit-Learn)
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
Scaler
scaler.com › home › topics › data-science › one hot encoding
One Hot encoding - Scaler Topics
May 4, 2023 - One Hot Encoding can be implemented in Python using Pandas or Scikit-learn library.
🌐
Medium
blog.cambridgespark.com › robust-one-hot-encoding-in-python-3e29bfcec77e
Tutorial: (Robust) One Hot Encoding in Python | by Kevin Lemagnen | Cambridge Spark
October 11, 2018 - We’ll need to specify handle_unknown as ignore so the OneHotEncoder can work later on with our unseen data. The OneHotEncoder will build a numpy array for our data, replacing our original features by one hot encoding versions.
🌐
MachineLearningMastery
machinelearningmastery.com › home › blog › how to one hot encode sequence data in python
How to One Hot Encode Sequence Data in Python - MachineLearningMastery.com
August 14, 2019 - In this tutorial, you will discover how to convert your input or output sequence data to a one hot encoding for use in sequence classification problems with deep learning in Python.
🌐
X
x.com › DeRonin_ › status › 2033587293064204349
Ronin on X: "https://t.co/J0ULhSHLLH" / X
March 16, 2026 - Covers why dense vector representations solve problems that one-hot encoding can't – specifically, capturing semantic relationships between items
🌐
Towards Data Science
towardsdatascience.com › home › data science › robust one-hot encoding
Robust One-Hot Encoding | Towards Data Science
April 26, 2024 - One-hot encoding is the practice of turning a factor variable that is stored in a column into dummy variables stored over multiple columns and represented as 0s and 1s. A simple example illustrates the concept.
🌐
Educative
educative.io › answers › one-hot-encoding-in-python
One-hot encoding in Python
Most of the existing machine learning algorithms cannot be executed on categorical data. Instead, the categorical data needs to first be converted to numerical data. One-hot encoding is one of the techniques used to perform this conversion.