Applying one-hot encoding to categorical data using Pandas
Pandas: Machine Learning Integration Exercise-6 with Solution
Write a Pandas program to apply one-hot encoding to categorical variables..
Following exercise shows how to apply one-hot encoding to categorical variables using Pandas' get_dummies().
Sample Solution :
Code :
import pandas as pd
# Load the dataset
df = pd.read_csv('data.csv')
# Apply one-hot encoding to the 'Gender' column
df_encoded = pd.get_dummies(df, columns=['Gender'])
# Output the one-hot encoded dataset
print(df_encoded)
Output:
ID Name Age Salary Target Gender_Female Gender_Male 0 1 Sara 25.0 50000.0 0 True False 1 2 Ophrah 30.0 60000.0 1 False True 2 3 Torben 22.0 70000.0 0 False True 3 4 Masaharu 35.0 80000.0 1 False True 4 5 Kaya NaN 55000.0 0 True False 5 6 Abaddon 29.0 NaN 1 False True
Explanation:
- Loaded the dataset using Pandas.
- Used pd.get_dummies() to apply one-hot encoding to the 'Gender' column.
- Displayed the one-hot encoded dataset.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics