• Post author:
  • Post category:Pandas
  • Post last modified:December 5, 2024
  • Reading time:16 mins read
You are currently viewing Pandas Convert Boolean to String in DataFrame

In Pandas, to convert Boolean values to strings in DataFrame, you can use the astype() function or the replace() method. This method allows you to change the data type of a DataFrame column, including converting Booleans (True/False) into strings (‘True’/’False’).

Advertisements

In this article, I will cover how to convert Boolean values to strings in a Pandas DataFrame. There are several methods available, depending on your specific needs, such as converting a single column, multiple columns, or applying custom logic.

Key Points –

  • Use astype(str) to easily convert Boolean columns to string values in a DataFrame.
  • You can apply astype(str) or replace() to multiple Boolean columns simultaneously by selecting multiple columns.
  • Apply the apply() function with a lambda expression for conditional string conversions based on more complex logic.
  • Use the map() function to map True and False to custom string values like "Yes"/"No" or other descriptive labels.
  • The replace() function can also be used for a more customized Boolean-to-string conversion.
  • Converting Boolean to string is useful when exporting data to formats like CSV or Excel, where Boolean values might not be properly displayed.

Create Pandas DataFrame

To convert Boolean to String in pandas DataFrame first, let’s create Pandas DataFrame with some test data. To use pandas you have to import it first using import pandas as pd.


import pandas as pd

# Sample DataFrame with Boolean values
data = {'column_name': [True, False, True, False], 'column_Score': [75, 80, 94, 60]}
df = pd.DataFrame(data)
print("Create DataFrame:\n", df)

Yields below output.

pandas convert boolean string

Convert Single Boolean Column Using astype()

To convert a single Boolean column to a string in a Pandas DataFrame using the astype() method.


# Convert the 'column_name' Boolean column to string
df['column_name'] = df['column_name'].astype(str)
print("DataFrame after converting 'column_name' to string:\n", df)

Here,

  • The astype(str) method converts the column_name Boolean values to string representations ("True" and "False").
  • The other column, column_Score, remains unchanged.
pandas convert boolean string

Convert Boolean to String Using replace()

Alternatively, to convert a Boolean column to strings using the replace() method in a Pandas DataFrame, you can specify the mappings for True and False to custom string values.


# Convert the 'column_name' Boolean column to string using replace()
df['column_name'] = df['column_name'].replace({True: 'Yes', False: 'No'})
print("DataFrame after converting 'column_name' to string using replace():\n", df)

# Output:
# DataFrame after converting 'column_name' to string using replace():
#   column_name  column_Score
# 0         Yes            75
# 1          No            80
# 2         Yes            94
# 3          No            60

Here,

  • The replace() method is used to map True to "Yes" and False to "No".
  • The resulting DataFrame has the column_name column converted to string representations while leaving the column_Score column unchanged.

Convert Boolean to Custom Strings Using map()

To convert a Boolean column to custom strings using the map() method in a Pandas DataFrame, you can specify a mapping for the True and False values to your desired strings.


# Convert the 'column_name' Boolean column to custom strings using map()
df['column_name'] = df['column_name'].map({True: 'Active', False: 'Inactive'})
print("DataFrame after converting 'column_name' to custom strings using map():\n", df)

# Output:
# DataFrame after converting 'column_name' to custom strings using map():
#   column_name  column_Score
# 0      Active            75
# 1    Inactive            80
# 2      Active            94
# 3    Inactive            60

Here,

  • The map() method is used to map True to "Active" and False to "Inactive".
  • The column_name column is now represented with custom string values while the column_Score column remains unchanged.

Convert Boolean Values with apply() for Conditional Customization

Similarly, to convert Boolean values to custom strings based on specific conditions using the apply() method in a Pandas DataFrame, you can define a function (or use a lambda function) that checks the Boolean value and returns the desired string.


# Use apply to convert Boolean values 
# To custom strings based on conditions
df['column_name'] = df['column_name'].apply(lambda x: 'Yes' if x else 'No')
print("DataFrame after converting 'column_name' to custom strings using apply():\n", df)
 
# Output:
# DataFrame after converting 'column_name' to custom strings using apply():
#   column_name  column_Score
# 0         Yes            75
# 1          No            80
# 2         Yes            94
# 3          No            60

Here,

  • The apply() method with a lambda function checks each value in the column_name column.
  • It converts True to "Yes" and False to "No" based on the condition specified in the lambda function.
  • The resulting DataFrame has the column_name column with customized string values while the column_Score column remains unchanged.

Convert Multiple Boolean Columns Using astype()

Finally, to convert multiple Boolean columns to strings in a Pandas DataFrame using the astype() method, you can select the desired columns and apply the conversion to them all at once.


import pandas as pd

# Sample DataFrame with multiple Boolean columns
data = {'column_name': [True, False, True, False], 
        'column_name1': [False, True, True, False],
        'column_Score': [75, 80, 94, 60]}
df = pd.DataFrame(data)

# Convert multiple Boolean columns to string using astype()
df[['column_name', 'column_name1']] = df[['column_name', 'column_name1']].astype(str)
print("DataFrame after converting Boolean columns to string:\n", df)

# Output:
# DataFrame after converting Boolean columns to string:
#   column_name column_name1  column_Score
# 0        True        False            75
# 1       False         True            80
# 2        True         True            94
# 3       False        False            60

Here,

  • The astype(str) method is applied to a subset of columns (column_name and column_name1) to convert their Boolean values to string representations ("True" and "False").
  • The column_Score remains unchanged.
  • This approach is efficient and allows for bulk conversions of multiple columns at once.

FAQ on Convert Boolean to String in Pandas DataFrame

What is the purpose of converting Boolean to string in a DataFrame?

Converting Boolean values to strings can enhance data readability, especially when exporting to formats like CSV or Excel. It can also be useful for reporting, visualization, or when preparing data for downstream applications that require string representations.

How can I convert a single Boolean column to a string?

You can use the astype(str) method to convert a single Boolean column to strings. For example: df['column_name'] = df['column_name'].astype(str).

What is the difference between replace() and map() for conversion?

replace() allows you to specify what each Boolean value should be replaced with, while map() is more flexible for mapping values to custom strings based on a specified mapping dictionary.

Can I customize the strings used for True and False?

You can customize the strings by using methods like replace() or map(). For example: df['column_name'] = df['column_name'].replace({True: 'Yes', False: 'No'}).

How can I check if the conversion was successful?

You can check the data types of the DataFrame columns using df.dtypes. After conversion, the Boolean columns should show as object type if they have been converted to strings.

Conclusion

In conclusion, converting Boolean values to strings in a Pandas DataFrame is a simple process that improves data readability and makes the data more suitable for exporting, reporting, or visualization. There are various methods to achieve this, including astype(), replace(), map(), and apply(), each offering flexibility depending on the specific requirements.

Happy Learning!!

Reference