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.

Answer from Napitupulu Jon on Stack Overflow
🌐
scikit-learn
scikit-learn.org › stable › modules › generated › sklearn.preprocessing.LabelEncoder.html
LabelEncoder — scikit-learn 1.9.1 documentation
class sklearn.preprocessing.LabelEncoder[source]# 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. Read more in the User Guide.
🌐
GeeksforGeeks
geeksforgeeks.org › machine learning › ml-label-encoding-of-datasets-in-python
Label Encoding in Python - GeeksforGeeks
Useful when encoding single categorical columns or target labels. Stores mapping inside .classes_ so we can retrieve original labels later. ... from sklearn.preprocessing import LabelEncoder import pandas as pd data = pd.DataFrame({ 'Fruit': ...
Published: June 11, 2026
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)
🌐
Medium
medium.com › @prathik.codes › labelencoder-in-scikit-learn-c1b7bccec412
LabelEncoder in scikit-learn. ML Quickies #24 | by Prathik C | Medium
October 9, 2025 - from sklearn.preprocessing import LabelEncoder # Example categorical labels y = ["cat", "dog", "cat", "bird"] # Create and fit the encoder le = LabelEncoder() y_encoded = le.fit_transform(y) print("Encoded labels:", y_encoded) Output: Encoded labels: [1 2 1 0] After fitting, LabelEncoder stores the unique categories it has seen in the .classes_ attribute, sorted alphabetically.
🌐
Codefinity
codefinity.com › courses › v2 › a65bbc96-309e-4df9-a790-a1eb8c815a1c › 1fce4aa9-710f-4bc9-ad66-16b4b2d30929 › 2d9a6807-ea36-4430-8cc5-2f1231fe6f81
Codefinity: Courses with certificates | Online Learning Platform
LabelEncoder encodes the target to numbers 0, 1, ... . 1234567891011121314 import pandas as pd from sklearn.preprocessing import LabelEncoder # Load the data and assign X, y variables df = pd.read_csv('https://codefinity-content-media.s3.eu...
🌐
GitHub
github.com › scikit-learn › scikit-learn › blob › main › sklearn › preprocessing › _label.py
scikit-learn/sklearn/preprocessing/_label.py at main · scikit-learn/scikit-learn
OneHotEncoder : Encode categorical features as a one-hot numeric array. · Examples · -------- `LabelEncoder` can be used to normalize labels. · >>> from sklearn.preprocessing import LabelEncoder ·
Author: scikit-learn
Find elsewhere
Top answer
1 of 4
213

There are some cases where LabelEncoder or DictVectorizor are useful, but these are quite limited in my opinion due to ordinality.

LabelEncoder can turn [dog,cat,dog,mouse,cat] into [1,2,1,3,2], but then the imposed ordinality means that the average of dog and mouse is cat. Still there are algorithms like decision trees and random forests that can work with categorical variables just fine and LabelEncoder can be used to store values using less disk space.

One-Hot-Encoding has the advantage that the result is binary rather than ordinal and that everything sits in an orthogonal vector space. The disadvantage is that for high cardinality, the feature space can really blow up quickly and you start fighting with the curse of dimensionality. In these cases, I typically employ one-hot-encoding followed by PCA for dimensionality reduction. I find that the judicious combination of one-hot plus PCA can seldom be beat by other encoding schemes. PCA finds the linear overlap, so will naturally tend to group similar features into the same feature.

2 of 4
58

While AN6U5 has given a very good answer, I wanted to add a few points for future reference. When considering One Hot Encoding(OHE) and Label Encoding, we must try and understand what model you are trying to build. Namely the two categories of model we will be considering are:

  1. Tree Based Models: Gradient Boosted Decision Trees and Random Forests.
  2. Non-Tree Based Models: Linear, kNN or Neural Network based.

Let's consider when to apply OHE and when to apply Label Encoding while building tree based models.

We apply OHE when:

  1. When the values that are close to each other in the label encoding correspond to target values that aren't close (non-linear data).
  2. When the categorical feature is not ordinal (dog, cat, mouse).

We apply Label encoding when:

  1. The categorical feature is ordinal (Jr. kg, Sr. kg, Primary school, high school, etc).
  2. When we can come up with a label encoder that assigns close labels to similar categories: This leads to less splits in the trees hence reducing the execution time.
  3. When the number of categorical features in the dataset is huge: One-hot encoding a categorical feature with huge number of values can lead to (1) high memory consumption and (2) the case when non-categorical features are rarely used by model. You can deal with the 1st case if you employ sparse matrices. The 2nd case can occur if you build a tree using only a subset of features. For example, if you have 9 numeric features and 1 categorical with 100 unique values and you one-hot-encoded that categorical feature, you will get 109 features. If a tree is built with only a subset of features, initial 9 numeric features will rarely be used. In this case, you can increase the parameter controlling size of this subset. In xgboost it is called colsample_bytree, in sklearn's Random Forest max_features.

In case you want to continue with OHE, as @AN6U5 suggested, you might want to combine PCA with OHE.

Let's consider when to apply OHE and Label Encoding while building non tree based models.

To apply Label encoding, the dependance between feature and target must be linear in order for Label Encoding to be utilised effectively.

Similarly, in case the dependance is non-linear, you might want to use OHE for the same.

Note: Some of the explanation has been referenced from How to Win a Data Science Competition from Coursera.

🌐
Medium
medium.com › @chandradip93 › labelencoder-a31a27763a9f
Labelencoder. LabelEncoder is a class in the… | by Chandradip Banerjee | Medium
March 7, 2023 - LabelEncoder is a class in the scikit-learn library that is used for encoding categorical (non-numeric) data into numerical labels. This is…
🌐
GitHub
github.com › openai › CLIP
GitHub - openai/CLIP: CLIP (Contrastive Language-Image Pretraining), Predict the most relevant text snippet given an image · GitHub
Note that this example uses the encode_image() and encode_text() methods that return the encoded features of given inputs. The example below uses scikit-learn to perform logistic regression on image features. import os import clip import torch import numpy as np from sklearn.linear_model import ...
Author: openai
🌐
DEV Community
dev.to › engrmark › when-to-use-labelencoder-and-onehotencoder-in-machine-learning-7gl
When to Use LabelEncoder and OneHotEncoder in Machine Learning - DEV Community
July 28, 2025 - Label Encoding simply assigns a number to each category, starting from 0. ... Use it when the categories have a natural order or ranking. Examples: ... Never use LabelEncoder for categories like colors or city names — because the model will ...
🌐
GeeksforGeeks
geeksforgeeks.org › machine learning › encoding-categorical-data-in-sklearn
Encoding Categorical Data in Sklearn - GeeksforGeeks
September 17, 2025 - Here we will use Label encoding converts each category into a unique integer, making it suitable for ordinal data or when models need numeric input. ... from sklearn.preprocessing import LabelEncoder le = LabelEncoder() df['class_encoded'] = ...
🌐
IBM
ibm.com › think › topics › machine-learning
What is Machine Learning? | IBM
August 26, 2025 - Labeling data can become prohibitively costly and time-consuming for complex tasks and large datasets. Self-supervised learning entails training on tasks in which a supervisory signal is obtained directly from unlabeled data—hence “self” supervised. For instance, autoencoders are trained to compress (or encode) input data, then reconstruct (or decode) the original input using that compressed representation.
🌐
Kaggle
kaggle.com › code › stephenmugisha › labelencoder
LabelEncoder
April 29, 2020 - Categorical Feature Encoding Challenge · Best Score · 0.76384 V1 · This Notebook has been released under the Apache 2.0 open source license. Input1 file · arrow_right_alt · Output0 files · arrow_right_alt · Logs5.1 second run - successful · arrow_right_alt ·
🌐
Udemy
udemy.com › development
Machine Learning A-Z [2026]: ML, DL, AI with AWS, Python & R
June 13, 2026 - This comprehensive guide to preprocessing categorical data covers essential techniques for handling missing values and encoding categorical variables in Python. Learn how to implement one-hot encoding for multi-category features and label encoding for binary outcomes using pandas and scikit-learn.
Rating: 4.5 ​ - ​ 206K votes
🌐
Pythonclass
pythonclass.in › labelencoder-sklearn.php
labelencoder sklearn | labelencoder scikit
labelencoder sklearn : The LabelEncoder in scikit-learn is used to encode the DataFrame of string labels. The data frame has columns above 50 and avoids creating LabelEncoder object for each column
🌐
scikit-learn
scikit-learn.org › stable › modules › generated › sklearn.preprocessing.TargetEncoder.html
TargetEncoder — scikit-learn 1.9.1 documentation
This unsupervised encoding is better suited for low cardinality categorical variables as it generate one new feature per unique category. ... Micci-Barreca, Daniele. “A preprocessing scheme for high-cardinality categorical attributes in classification and prediction problems” SIGKDD Explor. Newsl. 3, 1 (July 2001), 27–32. ... >>> import numpy as np >>> from sklearn.preprocessing import TargetEncoder >>> X = np.array([["dog"] * 20 + ["cat"] * 30 + ["snake"] * 38], dtype=object).T >>> y = [90.3] * 5 + [80.1] * 15 + [20.4] * 5 + [20.1] * 25 + [21.2] * 8 + [49] * 30 >>> enc_auto = TargetEncoder(smooth="auto") >>> X_trans = enc_auto.fit_transform(X, y)
🌐
OpenAI Developers
developers.openai.com › api › docs › guides › embeddings
Vector embeddings | OpenAI API
1 2 3 4 5 6 7 8 9import numpy as np from sklearn.cluster import KMeans matrix = np.vstack(df.ada_embedding.values) n_clusters = 4 kmeans = KMeans(n_clusters=n_clusters, init="k-means++", random_state=42) kmeans.fit(matrix) df["Cluster"] = kmeans.labels_ In Python, you can split a string into tokens with OpenAI’s tokenizer tiktoken. ... 1 2 3 4 5 6 7 8 9 10 11import tiktoken def num_tokens_from_string(string: str, encoding_name: str) -> int: """Returns the number of tokens in a text string.""" encoding = tiktoken.get_encoding(encoding_name) num_tokens = len(encoding.encode(string)) return num_tokens num_tokens_from_string("tiktoken is great!", "cl100k_base")
🌐
Arab Psychology
scales.arabpsychology.com › home › how can i use label encoding across multiple columns in scikit-learn?
How Can I Use Label Encoding Across Multiple Columns In Scikit-Learn?
June 27, 2024 - We can use the following code to perform label encoding to convert each categorical value in the team, position, and all_star columns into integer values: from sklearn.preprocessingimport LabelEncoder #perform label encoding across team, position, ...