🌐
Practical Business Python
pbpython.com β€Ί categorical-encoding.html
Guide to Encoding Categorical Values in Python - Practical Business Python
Since this article will only focus on encoding the categorical variables, we are going to include only the object columns in our dataframe. Pandas has a helpful select_dtypes function which we can use to build a new dataframe containing only the object columns.
🌐
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

python - How to encode a categorical variable in sklearn? - Stack Overflow
I'm trying to use the car evaluation dataset from the UCI repository and I wonder whether there is a convenient way to binarize categorical variables in sklearn. One approach would be to use the More on stackoverflow.com
🌐 stackoverflow.com
python - How to encode string categorical data? - Stack Overflow
So I have a dataset that is essentially the list of Windows API calls that a single program makes. Each row belongs to one program. Successive cells of the same row are the API calls made by the same More on stackoverflow.com
🌐 stackoverflow.com
machine learning - How to encode categorical values in Python - Stack Overflow
Given a vocabulary ["NY", "LA", "GA"], how can one encode it in such a way that it becomes: "NY" = 100 "LA" = 010 "GA" = 001 So if I do a lookup on "NY GA", I get 101 More on stackoverflow.com
🌐 stackoverflow.com
Encoding categorical values

Well, you're not using the results of your OneHotEncoder in the model, so...

ct.fit_transform(X_train) doesn't modify X_train.

More on reddit.com
🌐 r/learnpython
5
2
January 9, 2021
🌐
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'] = ...
🌐
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 - Label Encoding is the simplest form of encoding categorical variables. It assigns a unique integer value to each category. This technique works well when the categories have an inherent ordinal relationship (e.g., Low, Medium, High), but it ...
🌐
Analytics Vidhya
analyticsvidhya.com β€Ί home β€Ί what are categorical data encoding methods | binary encoding
What are Categorical Data Encoding Methods | Binary Encoding
May 1, 2025 - In the case when categories are more and binary encoding is not able to handle the dimensionality then we can use a larger base such as 4 or 8. Clear your Understanding how you can perform Lable Encoding in Python Β· #Import the libraries import category_encoders as ce import pandas as pd #Create the dataframe data=pd.DataFrame({'City':['Delhi','Mumbai','Hyderabad','Chennai','Bangalore','Delhi','Hyderabad','Mumbai','Agra']}) #Create an object for Base N Encoding encoder= ce.BaseNEncoder(cols=['city'],return_df=True,base=5) #Original Data data
🌐
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…
🌐
Scikit-learn course
inria.github.io β€Ί scikit-learn-mooc β€Ί python_scripts β€Ί 03_categorical_pipeline.html
Encoding of categorical variables β€” Scikit-learn course
Now, we can check the encoding applied on all categorical features. data_encoded = encoder.fit_transform(data_categorical) data_encoded[:5]
🌐
Medium
soumenatta.medium.com β€Ί categorical-data-encoding-techniques-in-python-a-complete-guide-a913aae19a22
Categorical Data Encoding Techniques in Python: A Complete Guide | by Dr. Soumen Atta, Ph.D. | Medium
May 4, 2023 - Scikit-learn is a popular library for machine learning in Python. Let’s start by importing the necessary libraries: import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder from sklearn.feature_extraction.text import CountVectorizer Β· We will be using the following dataset for our examples. This dataset contains information about different types of fruits and their characteristics. data = {'Fruit': ['Apple', 'Banana', 'Orange', 'Apple', 'Banana', 'Orange'], 'Color': ['Red', 'Yellow', 'Orange', 'Green', 'Yellow', 'Orange'], 'Price': [0.5, 0.25, 0.3, 0.6, 0.35, 0.4], 'Weight': [100, 120, 80, 110, 130, 90]} df = pd.DataFrame(data) print(df)
Find elsewhere
🌐
DataCamp
datacamp.com β€Ί tutorial β€Ί categorical-data
Handling Machine Learning Categorical Data with Python Tutorial | DataCamp
February 23, 2023 - ... Handling categorical data is an important aspect of many machine learning projects. In this tutorial, we have explored various techniques for analyzing and encoding categorical variables in Python, including one-hot encoding and label encoding, which are two commonly used techniques.
🌐
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.
🌐
Medium
niitdigital.medium.com β€Ί guide-to-encoding-categorical-values-in-python-eb91cee705d9
Guide to Encoding Categorical Values in Python | by NIIT Digital | Medium
August 4, 2021 - There is no specific rule for encoding categorical values in the Data Science world. Each approach has its pros and cons. But fortunately, python provides different tools for your various requirements to convert categorical data into suitable numeric values to enhance your model.
Top answer
1 of 3
31

if your data is a pandas DataFrame, then you can simply call get_dummies. Assume that your data frame is df, and you want to have one binary variable per level of variable 'key'. You can simply call:

pd.get_dummies(df['key'])

and then delete one of the dummy variables, to avoid the multi-colinearity problem. I hope this helps ...

2 of 3
16

The basic method is

import numpy as np
import pandas as pd, os
from sklearn.feature_extraction import DictVectorizer

def one_hot_dataframe(data, cols, replace=False):
    vec = DictVectorizer()
    mkdict = lambda row: dict((col, row[col]) for col in cols)
    vecData = pd.DataFrame(vec.fit_transform(data[cols].apply(mkdict, axis=1)).toarray())
    vecData.columns = vec.get_feature_names()
    vecData.index = data.index
    if replace is True:
        data = data.drop(cols, axis=1)
        data = data.join(vecData)
    return (data, vecData, vec)

data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
        'year': [2000, 2001, 2002, 2001, 2002],
        'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}

df = pd.DataFrame(data)

df2, _, _ = one_hot_dataframe(df, ['state'], replace=True)
print df2

Here is how to do in sparse format

import numpy as np
import pandas as pd, os
import scipy.sparse as sps
import itertools

def one_hot_column(df, cols, vocabs):
    mats = []; df2 = df.drop(cols,axis=1)
    mats.append(sps.lil_matrix(np.array(df2)))
    for i,col in enumerate(cols):
        mat = sps.lil_matrix((len(df), len(vocabs[i])))
        for j,val in enumerate(np.array(df[col])):
            mat[j,vocabs[i][val]] = 1.
        mats.append(mat)

    res = sps.hstack(mats)   
    return res

data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
        'year': ['2000', '2001', '2002', '2001', '2002'],
        'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}

df = pd.DataFrame(data)
print df

vocabs = []
vals = ['Ohio','Nevada']
vocabs.append(dict(itertools.izip(vals,range(len(vals)))))
vals = ['2000','2001','2002']
vocabs.append(dict(itertools.izip(vals,range(len(vals)))))

print vocabs

print one_hot_column(df, ['state','year'], vocabs).todense()
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 56521231 β€Ί how-to-encode-string-categorical-data
python - How to encode string categorical data? - Stack Overflow
from keras.utils import to_categorical data = ['cold', 'warm', 'hot'] # 3 possible values encoded = to_categorical(data) ... ~2000 different values will be converted to an 11-digit binary number, that means that in order to represent all different ...
🌐
Towards Data Science
towardsdatascience.com β€Ί home β€Ί data science β€Ί encoding categorical data, explained: a visual guide with code example for beginners
Encoding Categorical Data, Explained: A Visual Guide with Code Example for Beginners | Towards Data Science
September 2, 2024 - In Our Case: While our 'Windy' column only has two categories (Yes and No), we could use Binary Encoding to demonstrate the technique. It would result in a single binary column, where one category (e.g., No) is represented as 0 and the other (Yes) as 1. ... Target Encoding replaces each category with the mean of the target variable for that category. Common Use πŸ‘ : It's used when there's likely a relationship between the categorical variable and the target variable. It's particularly useful for high-cardinality features in datasets with a reasonable number of rows.
🌐
Medium
medium.com β€Ί data-science β€Ί categorical-encoding-techniques-93ebd18e1f24
Categorical Feature Encoding in Python | TDS Archive
April 4, 2020 - A guide for encoding binary, ordinal, and nominal categorical features in Python using sklearn and Pandas.
🌐
Medium
medium.com β€Ί aiskunks β€Ί categorical-data-encoding-techniques-d6296697a40f
Categorical Data Encoding Techniques | by Krishnakanth Naik Jarapala | AI Skunks | Medium
March 27, 2023 - Dummy encoding uses N-1 features to represent N labels/categories. ... One-Hot Encoding β€” N categories in a variable, N binary variables. Dummy encoding β€” N categories in a variable, N-1 binary variables. # Create a sample dataframe with categorical variable data = {'Color': ['Red', 'Green', 'Blue', 'Red', 'Blue']} df = pd.DataFrame(data) # Use get_dummies() function for dummy encoding dummy_df = pd.get_dummies(df['Color'], drop_first=True, prefix='Color') # Concatenate the dummy dataframe with the original dataframe df = pd.concat([df, dummy_df], axis=1)
🌐
Medium
garg-shelvi.medium.com β€Ί category-encoders-c2a9bb192f0a
How to Encode Categorical Data | by Shelvi Garg | Medium
July 12, 2022 - In this method, each category is mapped to a vector that contains 1 and 0 denoting the presence or absence of the feature. The number of vectors depends on the number of categories for features. ... ce_OHE = ce.OneHotEncoder(cols=['gender','city']) ce_OHEOneHotEncoder(cols=['gender', 'city'])data1 = ce_OHE.fit_transform(data) data1.head() Binary encoding converts a category into binary digits.
🌐
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