Built with Tutify.io

    AIStudyLabs

    Pandas Convert Boolean to String in DataFrame

    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').

    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 –

    <a id="h-create-pandas-dataframe"></a>

    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.

    <a id="h-convert-single-boolean-column-using-astype"></a>

    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,

    <a id="h-convert-boolean-to-string-using-replace"></a>

    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,

    <a id="h-convert-boolean-to-custom-strings-using-map"></a>

    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,

    <a id="h-convert-boolean-values-with-apply-for-conditional-customization"></a>

    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,

    <a id="h-convert-multiple-boolean-columns-using-astype"></a>

    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,

    <a id="h-faq-on-convert-boolean-to-string-in-pandas-dataframe"></a>

    FAQ on Convert Boolean to String in Pandas 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.

    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).

    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.

    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'}).

    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.

    <a id="h-conclusion"></a>

    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!!

    <a id="h-related-articles"></a>

    Related Articles

    <a id="h-reference"></a>

    Reference