Home » How to Convert Boolean Values to Integer Values in Pandas

How to Convert Boolean Values to Integer Values in Pandas

by Tutor Aspire

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

You may also like