Python - Change a column of yes or no to 1 or 0 in a pandas dataframe

Given a Pandas DataFrame consisting of a column having values int the form of either yes or no. We need to change these values to 1 or 0.
By Pranit Sharma Last updated : December 20, 2023

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.

Change a column of yes or no to 1 or 0 in a pandas dataframe

To change a column of yes or no to 1 or 0, we will use the map() method. This method will help us to traverse each value of DataFrame so that we can check the value at the same time. While accessing each value at some time, we will pass a dictionary inside it which will be having two keys; yes and no. We will assign 1 and 0 to these keys respectively.

Let us understand with the help of an example,

Python program to change a column of yes or no to 1 or 0 in a pandas dataframe

First let us create a dataframe and display the dataframe

Create and display DataFrame

# Importing pandas package
import pandas as pd

# Creating a Dictionary
d = {
    'Name':['Pooja','Meghna','Abhi','Sujata','Rohit'],
    'Insurance':['yes','no','no','yes','yes']
}

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

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

Output:

Example 1: Change a column of yes or no to 1 or 0

Change the column values using map()

Now, we will use the map() function to change the column values,

# Using map function
df['Insurance'] = df['Insurance'].map({'yes': 1, 'no': 0})

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

Output:

Example 2: Change a column of yes or no to 1 or 0

In this example, we have used the following Python topics that you should learn:

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.