Adding dummy columns to the original dataframe

Given a pandas dataframe, we have to add dummy columns to the given dataframe.
Submitted by Pranit Sharma, on September 25, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose, we are given a DataFrame of students with multiple attributes like roll number, name, year of admission, etc. We need to add a dummy column in this DataFrame.

Adding dummy columns in a dataframe

Dummy columns in pandas contain categorical data into dummy or indicator variables. These are used for data analysis. In most cases, this is a feature of any action being described.

To add columns / dummy columns in a DataFrame, you can use pd.get_dummies() method inside the method by specifying the column name and axis. Consider the below-given syntax:

pd.concat([df, pd.get_dummies(df['Year_of_admission'])], axis=1)

To get a dummy column, we must use pandas.get_dummies(), this method returns all the dummy values of each column passed as a series inside it.

Let us understand with the help of an example,

Python program to add dummy columns to the original dataframe

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original DataFrames
print("Created DataFrame:\n",df,"\n")

# Adding dummy column
df = pd.concat([df, pd.get_dummies(df['Year_of_admission'])], axis=1)

# Display result
print("Modified DataFrame:\n",df)


The output of the above program is:

Example: Adding dummy columns

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.