How to replace by Categorical variables using Pandas

0 min

When processing data you will encounter cases where you need to replace numeric data by categorical variables and vice versa.

This is how to do it using Pandas using the .replace() method.

Numeric to Categorical

# We import the libraries
import pandas as pd

# Create our example DataFrame
names = ["Johanna", "Jack", 
         "Elena", "Bob", 
ages = [24, 42, 18, 23, 75]
gender = [2, 1, 2, 1, 2]

df = pd.DataFrame({"name": names,
                   "ages": ages,
                   "gender": gender})

# We replace our numeric data
# of the gender column into
# categorical variable 
df["gender"] = df["gender"].replace({1:'Male', 
                                     2 :'Female'})

# We print our dataframe
Changing 1 into Male and 2 into Female

Here you are ! You now know how to transform numeric variable into categorical variable.