
- Python Pandas - Home
- Python Pandas - Introduction
- Python Pandas - Environment Setup
- Python Pandas - Basics
- Python Pandas - Introduction to Data Structures
- Python Pandas - Index Objects
- Python Pandas - Panel
- Python Pandas - Basic Functionality
- Python Pandas - Indexing & Selecting Data
- Python Pandas - Series
- Python Pandas - Series
- Python Pandas - Slicing a Series Object
- Python Pandas - Attributes of a Series Object
- Python Pandas - Arithmetic Operations on Series Object
- Python Pandas - Converting Series to Other Objects
- Python Pandas - DataFrame
- Python Pandas - DataFrame
- Python Pandas - Accessing DataFrame
- Python Pandas - Slicing a DataFrame Object
- Python Pandas - Modifying DataFrame
- Python Pandas - Removing Rows from a DataFrame
- Python Pandas - Arithmetic Operations on DataFrame
- Python Pandas - IO Tools
- Python Pandas - IO Tools
- Python Pandas - Working with CSV Format
- Python Pandas - Reading & Writing JSON Files
- Python Pandas - Reading Data from an Excel File
- Python Pandas - Writing Data to Excel Files
- Python Pandas - Working with HTML Data
- Python Pandas - Clipboard
- Python Pandas - Working with HDF5 Format
- Python Pandas - Comparison with SQL
- Python Pandas - Data Handling
- Python Pandas - Sorting
- Python Pandas - Reindexing
- Python Pandas - Iteration
- Python Pandas - Concatenation
- Python Pandas - Statistical Functions
- Python Pandas - Descriptive Statistics
- Python Pandas - Working with Text Data
- Python Pandas - Function Application
- Python Pandas - Options & Customization
- Python Pandas - Window Functions
- Python Pandas - Aggregations
- Python Pandas - Merging/Joining
- Python Pandas - MultiIndex
- Python Pandas - Basics of MultiIndex
- Python Pandas - Indexing with MultiIndex
- Python Pandas - Advanced Reindexing with MultiIndex
- Python Pandas - Renaming MultiIndex Labels
- Python Pandas - Sorting a MultiIndex
- Python Pandas - Binary Operations
- Python Pandas - Binary Comparison Operations
- Python Pandas - Boolean Indexing
- Python Pandas - Boolean Masking
- Python Pandas - Data Reshaping & Pivoting
- Python Pandas - Pivoting
- Python Pandas - Stacking & Unstacking
- Python Pandas - Melting
- Python Pandas - Computing Dummy Variables
- Python Pandas - Categorical Data
- Python Pandas - Categorical Data
- Python Pandas - Ordering & Sorting Categorical Data
- Python Pandas - Comparing Categorical Data
- Python Pandas - Handling Missing Data
- Python Pandas - Missing Data
- Python Pandas - Filling Missing Data
- Python Pandas - Interpolation of Missing Values
- Python Pandas - Dropping Missing Data
- Python Pandas - Calculations with Missing Data
- Python Pandas - Handling Duplicates
- Python Pandas - Duplicated Data
- Python Pandas - Counting & Retrieving Unique Elements
- Python Pandas - Duplicated Labels
- Python Pandas - Grouping & Aggregation
- Python Pandas - GroupBy
- Python Pandas - Time-series Data
- Python Pandas - Date Functionality
- Python Pandas - Timedelta
- Python Pandas - Sparse Data Structures
- Python Pandas - Sparse Data
- Python Pandas - Visualization
- Python Pandas - Visualization
- Python Pandas - Additional Concepts
- Python Pandas - Caveats & Gotchas
Python Pandas - Computing Dummy Variables
Dummy variables, also known as indicator variables, are binary (0 or 1) variables created to represent categorical data numerically. In data analysis, particularly when working with categorical data, it is often necessary to convert categorical variables into a numerical format. Converting categorical variables into dummy variables is essential for statistical modeling and machine learning, where numerical inputs are required.
Pandas provides two key functions for handling dummy variables −
get_dummies(): Converts categorical data into dummy/indicator variables.
from_dummies(): Reconstructs the original categorical variable from dummy variables.
In this tutorial, we will explore how to create dummy variables using get_dummies(), customize them with prefixes, handle collinearity, and revert them back to categorical format using from_dummies().
Creating Dummy Variables with get_dummies()
The get_dummies() function in Pandas is used to convert categorical variables of a Series or a DataFrame into dummy variables.
Example: Basic example of creating the Dummy Variables
Here is a basic example of creates dummy variables using the pandas.get_dummies() function.
import pandas as pd import numpy as np # Create a DataFrame df = pd.DataFrame({"keys": list("aeeioou"), "values": range(7)}) # Display the Input DataFrame print('Input DataFrame:\n',df) # Create dummy variables for the keys column dummies = pd.get_dummies(df["keys"]) print('Resultant Dummy Variables:\n',dummies)
Following is the output of the above code −
Input DataFrame:
keys | values |
---|---|
a | 0 |
e | 1 |
e | 2 |
i | 3 |
o | 4 |
o | 5 |
u | 6 |
a | e | i | o | u | |
---|---|---|---|---|---|
0 | True | False | False | False | False |
1 | False | True | False | False | False |
2 | False | True | False | False | False |
3 | False | False | True | False | False |
4 | False | False | False | True | False |
5 | False | False | False | True | False |
6 | False | False | False | False | True |
Creating Dummy Variables with Prefix
The get_dummies() function allows you to add a prefix to the dummy variable column names when converting the categorical variables of a Pandas objects into dummy variables by using the prefix parameter.
Example
This example demonstrates creating dummy variables with a prefix using the pandas.get_dummies() function.
import pandas as pd import numpy as np # Create a DataFrame df = pd.DataFrame({"keys": list("aeeioou"), "values": range(7)}) # Display the Input DataFrame print('Input DataFrame:\n',df) # Create dummy variables for the keys column dummies = pd.get_dummies(df["keys"], prefix="Col_") print('Resultant Dummy Variables with Prefix:\n',dummies)
Following is the output of the above code −
Input DataFrame:
keys | values |
---|---|
a | 0 |
e | 1 |
e | 2 |
i | 3 |
o | 4 |
o | 5 |
u | 6 |
Col__a | Col__e | Col__i | Col__o | Col__u | |
---|---|---|---|---|---|
0 | True | False | False | False | False |
1 | False | True | False | False | False |
2 | False | True | False | False | False |
3 | False | False | True | False | False |
4 | False | False | False | True | False |
5 | False | False | False | True | False |
6 | False | False | False | False | True |
Handling Collinearity While Creating Dummy Variables
To avoid collinearity issues in statistical models, you can drop the first dummy variable by setting the drop_first parameter to True.
Example
This example drops the first dummy variable using the drop_first parameter of the pandas.get_dummies() function.
import pandas as pd import numpy as np # Create a DataFrame df = pd.DataFrame({"keys": list("aeeioou"), "values": range(7)}) # Display the Input DataFrame print('Input DataFrame:\n',df) # Create dummy variables for the keys column dummies = pd.get_dummies(df["keys"], drop_first=True) print('Resultant Dummy Variables with Prefix:\n',dummies)
Following is the output of the above code −
Input DataFrame:
keys | values |
---|---|
a | 0 |
e | 1 |
e | 2 |
i | 3 |
o | 4 |
o | 5 |
u | 6 |
e | i | o | u | |
---|---|---|---|---|
0 | False | False | False | False |
1 | True | False | False | False |
2 | True | False | False | False |
3 | False | True | False | False |
4 | False | False | True | False |
5 | False | False | True | False |
6 | False | False | False | True |
Creating Categorical Variables from Dummies
The pandas.from_dummies() function is used to convert the output of get_dummies() back into a categorical Series.
Example
This example demonstrates creating a categorical Series from dummy variables using the pandas.from_dummies() function.
import pandas as pd import numpy as np # Create a DataFrame with dummy variables df = pd.DataFrame({"Col_a": [0, 1, 0], "Col_b": [1, 0, 1]}) # Display the Input DataFrame print('Input DataFrame:\n',df) # Convert the dummy variables back to categorical original_series = pd.from_dummies(df, sep="_") print('Resultant Categorical Variables:\n',original_series )
Following is the output of the above code −
Input DataFrame:
Col_a | Col_b |
---|---|
0 | 1 |
1 | 0 |
0 | 1 |
Col |
---|
b |
a |
b |