🌐
GeeksforGeeks
geeksforgeeks.org › machine learning › ml-label-encoding-of-datasets-in-python
Label Encoding in Python - GeeksforGeeks
The encoded labels are typically assigned based on the sorted order of unique categories. Produces a compact representation of categorical data using a single feature column. Commonly applied to target variables and ordinal features in machine ...
Published: June 11, 2026
🌐
Great Learning
mygreatlearning.com › blog › ai and machine learning › label encoding in python
What is Label Encoding in Python | Great Learning
December 18, 2024 - In label encoding in python, we replace the categorical value with a numeric value between 0 and the number of classes minus 1. Learn more!
Discussions

Please help me in understanding when to use label encoding and when to use one hot encoding ? What should be the data type.. If you could point out to a few articles that would help me understand..
Short version: Use label encoding if the labels can be ranked. For example “poor”, “average”, and “good” since poor < average < good. If label ranking doesn’t make sense, then one hot encoding is a better choice. For example “red”, “blue”, “yellow” are not really rankable. However, it is not always so straight forward. Using label encoding on say tshirt sizes as a feature to predict weight is probably ok. But probably not if the tshirt size was used as a feature to predict their favorite beer. More on reddit.com
🌐 r/learnmachinelearning
8
34
May 14, 2021
Why is Label Encoding these categorical features in order increasing the CV score?
Also: it doesn't seem like it's a case where my method is overfitting or something, because both the train and test scores are worse. More on reddit.com
🌐 r/datascience
12
6
May 17, 2018
🌐
scikit-learn
scikit-learn.org › stable › modules › generated › sklearn.preprocessing.LabelEncoder.html
LabelEncoder — scikit-learn 1.9.1 documentation
Encode target labels with value between 0 and n_classes-1. This transformer should be used to encode target values, i.e. y, and not the input X.
🌐
Analytics Vidhya
analyticsvidhya.com › home › how to perform label encoding in python?
Label Encoding in Python Explained with Examples
December 19, 2023 - Categorical variables in Python can be transformed into numerical labels using the label encoding technique. It gives each category in a variable a distinct numerical value, enabling machine learning algorithms to interpret and analyze the data ...
🌐
Statology
statology.org › home › how to perform label encoding in python (with example)
How to Perform Label Encoding in Python (With Example)
August 26, 2022 - Often in machine learning, we want ... One way to do this is through label encoding, which assigns each categorical value an integer value based on alphabetical order....
🌐
Educative
educative.io › answers › label-encoding-in-python
Label encoding in Python
Line 9: We use the fit_transform method of the encoder object and pass the 1-dimensional array which is to be encoded. We store the encoded array in the encoded_col variable. Line 10: We replace the Fruits column data with the encoded_col data. Line 11: We display the updated data frame with label encoded column.
🌐
DataCamp
campus.datacamp.com › courses › working-with-categorical-data-in-python › pitfalls-and-encoding
Label encoding | Python
Label encoding is a technique that codes categorical values as integers. In Python, these codes often start at 0 and end at n - 1, where n is the number of categories. A -1 code is often used to indicate any missing values. Label encoding is used to save memory and to simplify responses when ...
🌐
Medium
medium.com › @kattilaxman4 › a-practical-guide-for-python-label-encoding-with-python-fb0b0e7079c5
A Practical Guide for Python: Label Encoding with Python | by Kattilaxman | Medium
October 25, 2023 - However, it is important to note that label encoding should be used with caution, especially when dealing with features with a high number of categories. The reason is that label encoding introduces ordinality into the data, which does not exist in Python.
Find elsewhere
🌐
Medium
medium.com › @vtalladin06 › label-encoding-in-python-ec0bbe6f0e0f
Label Encoding in Python. Introduction: | by Tahseen Alladin | Medium
February 1, 2024 - Label encoding can be useful when ... assigning numerical values accordingly. ... In Python, scikit-learn (sklearn) provides the LabelEncoder class for label encoding....
🌐
AskPython
askpython.com › python › examples › label-encoding
Label Encoding in Python - A Quick Guide! - AskPython
February 16, 2023 - For example, if a dataset contains a variable ‘Gender’ with labels ‘Male’ and ‘Female’, then the label encoder would convert these labels into a number format and the resultant outcome would be [0,1]. Thus, by converting the labels into the integer format, the machine learning model can have a better understanding in terms of operating the dataset. Python sklearn library provides us with a pre-defined function to carry out Label Encoding on the dataset.
🌐
PyShark
pyshark.com › home › label encoding in python
Label Encoding in Python - Machine Learning - PyShark
January 4, 2024 - Learn how to do label encoding in python by converting labels into numeric form. Examples using scikit learn and pandas for label encoding.
🌐
Spot Intelligence
spotintelligence.com › home › practical guide and tutorial to label encoding in python
Practical Guide And Tutorial To Label Encoding In Python
October 11, 2024 - In this example, we create a DataFrame with a categorical column ‘Category’ and then use the pd. factorize method to perform label encoding. The encoded values are stored in a new column, ‘Category_encoded.’ · See also SimHash — The Ultimate Guide And How To Get Started Guide In Python
🌐
Javatpoint
javatpoint.com › label-encoding-in-python
Label Encoding in Python - Javatpoint
Label Encoding in Python with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, operators, etc.
🌐
Jaro Education
jaroeducation.com › home › blog › label encoding in python
Python Implementation of Label Encoding in 2024
3 days ago - Label encoding in Python can be performed using scikit-learn library LabelEncoder class which is part of the pre-processing module. However, this module is not activated by default while using a Python interpreter or using any Python IDE such ...
🌐
Medium
medium.com › @sunnykumar1516 › what-is-label-encoding-application-of-label-encoder-in-machine-learning-and-deep-learning-models-c593669483ed
label encoding. what is label encoding. label encoding in machine learning. sklearn label encoding . python label encoding. python label encoder | Medium
January 12, 2024 - I would suggest you to go through this article to understand types of categorical data types. Label encoding is a process in machine learning where categorical data, represented as labels or strings, is converted into numerical format.
🌐
GeeksforGeeks
geeksforgeeks.org › videos › label-encoding-in-python
Label Encoding in Python - GeeksforGeeks | Videos
Using factorize() Function: Pandas’ factorize() function assigns a unique integer to each category, making it a convenient option for label encoding. It also returns the unique labels, which can be useful for understanding the mapping between categories and their numerical values. Scikit-learn is a popular machine learning library in Python that provides a dedicated LabelEncoder class for label encoding.
Published: September 5, 2024
Views: 22K
🌐
Analytics Vidhya
analyticsvidhya.com › home › one hot encoding vs label encoding in machine learning
One Hot Encoding vs Label Encoding in Machine Learning
April 23, 2025 - Let’s walk through how to implement label encoding using both Pandas and the Scikit-Learn libraries in Python:
Top answer
1 of 16
609

You can easily do this though,

df.apply(LabelEncoder().fit_transform)

EDIT2:

In scikit-learn 0.20, the recommended way is

OneHotEncoder().fit_transform(df)

as the OneHotEncoder now supports string input. Applying OneHotEncoder only to certain columns is possible with the ColumnTransformer.

EDIT:

Since this original answer is over a year ago, and generated many upvotes (including a bounty), I should probably extend this further.

For inverse_transform and transform, you have to do a little bit of hack.

from collections import defaultdict
d = defaultdict(LabelEncoder)

With this, you now retain all columns LabelEncoder as dictionary.

# Encoding the variable
fit = df.apply(lambda x: d[x.name].fit_transform(x))

# Inverse the encoded
fit.apply(lambda x: d[x.name].inverse_transform(x))

# Using the dictionary to label future data
df.apply(lambda x: d[x.name].transform(x))

MOAR EDIT:

Using Neuraxle's FlattenForEach step, it's possible to do this as well to use the same LabelEncoder on all the flattened data at once:

FlattenForEach(LabelEncoder(), then_unflatten=True).fit_transform(df)

For using separate LabelEncoders depending for your columns of data, or if only some of your columns of data needs to be label-encoded and not others, then using a ColumnTransformer is a solution that allows for more control on your column selection and your LabelEncoder instances.

2 of 16
132

As mentioned by larsmans, LabelEncoder() only takes a 1-d array as an argument. That said, it is quite easy to roll your own label encoder that operates on multiple columns of your choosing, and returns a transformed dataframe. My code here is based in part on Zac Stewart's excellent blog post found here.

Creating a custom encoder involves simply creating a class that responds to the fit(), transform(), and fit_transform() methods. In your case, a good start might be something like this:

import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import Pipeline

# Create some toy data in a Pandas dataframe
fruit_data = pd.DataFrame({
    'fruit':  ['apple','orange','pear','orange'],
    'color':  ['red','orange','green','green'],
    'weight': [5,6,3,4]
})

class MultiColumnLabelEncoder:
    def __init__(self,columns = None):
        self.columns = columns # array of column names to encode

    def fit(self,X,y=None):
        return self # not relevant here

    def transform(self,X):
        '''
        Transforms columns of X specified in self.columns using
        LabelEncoder(). If no columns specified, transforms all
        columns in X.
        '''
        output = X.copy()
        if self.columns is not None:
            for col in self.columns:
                output[col] = LabelEncoder().fit_transform(output[col])
        else:
            for colname,col in output.iteritems():
                output[colname] = LabelEncoder().fit_transform(col)
        return output

    def fit_transform(self,X,y=None):
        return self.fit(X,y).transform(X)

Suppose we want to encode our two categorical attributes (fruit and color), while leaving the numeric attribute weight alone. We could do this as follows:

MultiColumnLabelEncoder(columns = ['fruit','color']).fit_transform(fruit_data)

Which transforms our fruit_data dataset from

to

Passing it a dataframe consisting entirely of categorical variables and omitting the columns parameter will result in every column being encoded (which I believe is what you were originally looking for):

MultiColumnLabelEncoder().fit_transform(fruit_data.drop('weight',axis=1))

This transforms

to

.

Note that it'll probably choke when it tries to encode attributes that are already numeric (add some code to handle this if you like).

Another nice feature about this is that we can use this custom transformer in a pipeline:

encoding_pipeline = Pipeline([
    ('encoding',MultiColumnLabelEncoder(columns=['fruit','color']))
    # add more pipeline steps as needed
])
encoding_pipeline.fit_transform(fruit_data)
🌐
Codeloop
codeloop.org › home › python machine learning label encoding
Python Machine Learning Label Encoding - Codeloop
May 12, 2024 - For example, if you have categories like “red,” “green,” and “blue,” label encoding would assign them integers like 0, 1, and 2. ... For labeling data for machine learning in Python, you can use the LabelEncoder class from the sklearn.preprocessing module.
🌐
Practical Business Python
pbpython.com › categorical-encoding.html
Guide to Encoding Categorical Values in Python - Practical Business Python
We could choose to encode it like this: ... One trick you can use in pandas is to convert a column to a category, then use those category values for your label encoding: