How to replace by Categorical variables using Pandas

0 min readDataFrameData ManipulationData ScienceData
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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", 
         "Annie"]
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
print(df)
Changing 1 into Male and 2 into Female

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

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.