Have you ever tried to encode ordinal categorical features by making a simple function which is quiet easy to understand and change.
So this is the recipe on how we can encode ordinal categorical features in Python.
import pandas as pd
We have imported pandas which will be needed for the dataset.
We have created a dataframe with one feature "score" with categorical variables "Low", "Medium" and "High".
df = pd.DataFrame({"Score": ["Low", "Low", "Medium", "Medium", "High", "Low", "Medium","High", "Low"]})
print(df)
We have created an object scale_mapper in which we have passed the encoding parameter i.e putting numerical values instead of categorical variable. We have made a feature scale in which there will be numerical encoded values.
scale_mapper = {"Low":1, "Medium":2, "High":3}
df["Scale"] = df["Score"].replace(scale_mapper)
print(df)
So the output comes as:
Score 0 Low 1 Low 2 Medium 3 Medium 4 High 5 Low 6 Medium 7 High 8 Low Score Scale 0 Low 1 1 Low 1 2 Medium 2 3 Medium 2 4 High 3 5 Low 1 6 Medium 2 7 High 3 8 Low 1