11.1 C
London
Sunday, July 7, 2024
HomePandas in PythonGeneral Functions in PythonHow to Convert Boolean Values to Integer Values in Pandas

How to Convert Boolean Values to Integer Values in Pandas

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following basic syntax to convert a column of boolean values to a column of integer values in pandas:

df.column1 = df.column1.replace({True: 1, False: 0})

The following example shows how to use this syntax in practice.

Example: Convert Boolean to Integer in Pandas

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
                   'points': [18, 22, 19, 14, 14, 11, 20],
                   'playoffs': [True, False, False, False, True, False, True]})

#view DataFrame
df

We can use dtypes to quickly check the data type of each column:

#check data type of each column
df.dtypes

team        object
points       int64
playoffs      bool
dtype: object

We can see that the ‘playoffs’ column is of type boolean.

We can use the following code to quickly convert the True/False values in the ‘playoffs’ column into 1/0 integer values:

#convert 'playoffs' column to integer
df.playoffs = df.playoffs.replace({True: 1, False: 0})

#view updated DataFrame
df

	team	points	playoffs
0	A	18	1
1	B	22	0
2	C	19	0
3	D	14	0
4	E	14	1
5	F	11	0
6	G	20	1

Each True value was converted to 1 and each False value was converted to 0.

We can use dtypes again to verify that the ‘playoffs’ column is now an integer:

#check data type of each column
df.dtypes

team        object
points       int64
playoffs     int64
dtype: object

We can see that the ‘playoffs’ column is now of type int64.

Additional Resources

The following tutorials explain how to perform other common operations in pandas:

How to Convert Categorical Variable to Numeric in Pandas
How to Convert Pandas DataFrame Columns to int
How to Convert DateTime to String in Pandas

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories