Search code examples
pythonpandasdataframecolorshighlight

How to color boolean values by different colors in pandas dataframe


Customer_id   Name    Age  Balance
        Q1   True   True     True
        W2   True   True     True
        E3   True  False     True
        T5   True   True    False
        Y6   True   True     True
        U7   True   True     True
        I8  False  False    False
        O9   True  False    False
        P0  False  False    False

I want to highlight or color a word 'TRUE' in yellow in the above dataframe

Here is my code which I tried:

def color_negative_red(val):
    color = 'yellow' if val == 'TRUE' else 'black'
    return 'color: %s' % color
df = dataframe.style.\
       apply(color_negative_red).\
       to_excel('df.xlsx')

and I am getting the below error

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index Customer_id')

What am I doing wrong here?


Solution

  • Use Styler.applymap instead apply:

    dataframe.style.\
           applymap(color_negative_red).\
           to_excel('df.xlsx')
    

    You can also compare by True if boolean and 'True' if string:

    def color_negative_red(val):
        color = 'yellow' if val == True else 'black'
        return 'color: %s' % color
    
    #python 3.6+ with f-strings
    def color_negative_red(val):
        color = 'yellow' if val == True else 'black'
        return f'color: {color}'
    
    #python bellow 3.6
    def color_negative_red(val):
        color = 'yellow' if val == True else 'black'
        return 'color: {}'.format(color)
    

    pic

    If want also remove index values:

    dataframe.style.\
           applymap(color_negative_red).\
           to_excel('df.xlsx', index=False)
    

    pic1