Convert Boolean Column to String Object in pandas DataFrame in Python (Example Code)
In this article, I’ll explain how to transform a True/False boolean column to the string data type in a pandas DataFrame in Python programming.
Setting up the Example
import pandas as pd # Import pandas library in Python |
import pandas as pd # Import pandas library in Python
my_df = pd.DataFrame({'A':[False, True, False, False, True, False], # Construct a pandas DataFrame 'B':range(10, 16)}) print(my_df) # A B # 0 False 10 # 1 True 11 # 2 False 12 # 3 False 13 # 4 True 14 # 5 False 15 |
my_df = pd.DataFrame({'A':[False, True, False, False, True, False], # Construct a pandas DataFrame 'B':range(10, 16)}) print(my_df) # A B # 0 False 10 # 1 True 11 # 2 False 12 # 3 False 13 # 4 True 14 # 5 False 15
Example: Converting a Boolean to a String Using replace() Function
my_df['A'] = my_df['A'].replace({True: 'x', False: 'y'}) # Transform boolean to string print(my_df) # A B # 0 y 10 # 1 x 11 # 2 y 12 # 3 y 13 # 4 x 14 # 5 y 15 |
my_df['A'] = my_df['A'].replace({True: 'x', False: 'y'}) # Transform boolean to string print(my_df) # A B # 0 y 10 # 1 x 11 # 2 y 12 # 3 y 13 # 4 x 14 # 5 y 15
print(my_df.dtypes) # Print data types of all columns # A object # B int64 # dtype: object |
print(my_df.dtypes) # Print data types of all columns # A object # B int64 # dtype: object
Related Tutorials
Below, you may find some additional resources that are similar to the topic of this page.