Home >Backend Development >Python Tutorial >How to Perform Label Encoding Across Multiple Columns in Scikit-Learn?

How to Perform Label Encoding Across Multiple Columns in Scikit-Learn?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 02:53:021030browse

How to Perform Label Encoding Across Multiple Columns in Scikit-Learn?

Label Encoding across Multiple Columns in Scikit-Learn

When dealing with datasets containing multiple columns of categorical data, it becomes necessary to encode these labels numerically for use in machine learning algorithms. Scikit-learn provides the LabelEncoder class for this purpose. However, directly applying it to a DataFrame with numerous columns (e.g., 50) can lead to an error due to an incorrect input shape.

To overcome this challenge, an elegant way to perform label encoding across all columns simultaneously is:

df.apply(LabelEncoder().fit_transform)

As an alternative, especially for scikit-learn versions 0.20 and above, consider using OneHotEncoder:

OneHotEncoder().fit_transform(df)

OneHotEncoder natively supports string inputs and generates one-hot encoded vectors.

Alternatively, if you require control over the LabelEncoder instances for different columns or only need to encode a subset of columns, you can use ColumnTransformer:

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import LabelEncoder

transformer = ColumnTransformer(
    transformers=[('labels', LabelEncoder(), ['column1', 'column2'])],
)

transformed_data = transformer.fit_transform(df)

By using ColumnTransformer, you can specify the columns to be encoded and maintain separate LabelEncoder instances, allowing for greater flexibility in your data preparation.

The above is the detailed content of How to Perform Label Encoding Across Multiple Columns in Scikit-Learn?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn