Convert String Column to Boolean Data Type in pandas DataFrame in Python (Example Code)

In this tutorial you’ll learn how to transform a string column to a boolean data type in a pandas DataFrame in Python.

Setting up the Example

import pandas as pd                                        # Load pandas library
my_df = pd.DataFrame({'A':['x', 'x', 'y', 'x', 'x', 'y'],  # Construct a pandas DataFrame
                      'B':range(10, 16)})
print(my_df)
#    A   B
# 0  x  10
# 1  x  11
# 2  y  12
# 3  x  13
# 4  x  14
# 5  y  15

Example: Converting a String to a Boolean Using replace() Function

my_df['A'] = my_df['A'].replace({'x': True, 'y': False})   # Transform string to boolean
print(my_df)
#        A   B
# 0   True  10
# 1   True  11
# 2  False  12
# 3   True  13
# 4   True  14
# 5  False  15
print(my_df.dtypes)                                        # Print data types of all columns
# A     bool
# B    int64
# dtype: object

Further Resources & Related Articles

In addition, you could have a look at some of the other Python articles that I have published on my homepage. I have released several articles already.

Leave a Reply

Your email address will not be published.

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