Title: Encoding Ordinal Categorical Features
Slug: encoding_ordinal_categorical_features
Summary: How to encode ordinal categorical features for machine learning in Python.
Date: 2016-09-06 12:00
Category: Machine Learning
Tags: Preprocessing Structured Data
Authors: Chris Albon

Preliminaries


In [1]:
# Load library
import pandas as pd

Create Feature Matrix


In [6]:
# Create features
df = pd.DataFrame({'Score': ['Low', 
                             'Low', 
                             'Medium', 
                             'Medium', 
                             'High']})

# View data frame
df


Out[6]:
Score
0 Low
1 Low
2 Medium
3 Medium
4 High

Create Scale Map


In [7]:
# Create mapper
scale_mapper = {'Low':1, 
                'Medium':2,
                'High':3}

Map Scale To Features


In [8]:
# Map feature values to scale
df['Scale'] = df['Score'].replace(scale_mapper)

# View data frame
df


Out[8]:
Score Scale
0 Low 1
1 Low 1
2 Medium 2
3 Medium 2
4 High 3