Convert Integer Column to Boolean Data Type in pandas DataFrame in Python (3 Examples)

This tutorial explains how to convert an integer column to the boolean data type in a pandas DataFrame in Python programming.

Setting up the Examples

import pandas as pd                         # Import pandas library in Python
df = pd.DataFrame({'A':[1, 1, 0, 1, 0],     # Constructing a pandas DataFrame
                   'B':[0, 1, 1, 0, 1],
                   'C':[1, 1, 1, 1, 0]})
print(df)
#    A  B  C
# 0  1  0  1
# 1  1  1  1
# 2  0  1  1
# 3  1  0  1
# 4  0  1  0
print(df.dtypes)                            # Printing the data types of all columns
# A    int64
# B    int64
# C    int64
# dtype: object

Example 1: Transforming One Column of a pandas DataFrame from Integer to Boolean

df1 = df.copy()                             # Duplicate pandas DataFrame
df1['A'] = df1['A'].astype(bool)            # Converting integer to boolean
print(df1.dtypes)                           # Printing the data types of all columns
# A     bool
# B    int64
# C    int64
# dtype: object

Example 2: Transforming Multiple Columns of a pandas DataFrame from Integer to Boolean

df2 = df.copy()                             # Duplicate pandas DataFrame
df2 = df2.astype({'A': bool, 'C': bool})    # Converting integer to boolean
print(df2.dtypes)                           # Printing the data types of all columns
# A     bool
# B    int64
# C     bool
# dtype: object

Example 3: Transforming Each Column of a pandas DataFrame from Integer to Boolean

df3 = df.copy()                             # Duplicate pandas DataFrame
df3 = df3.astype(bool)                      # Converting integer to boolean
print(df3.dtypes)                           # Printing the data types of all columns
# A    bool
# B    bool
# C    bool
# dtype: object

Related Articles

You may find some related Python tutorials on topics such as naming data, counting, and groups below:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top