首页 > 解决方案 > 如何在熊猫数据框中用不同颜色为布尔值着色

问题描述

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

我想'TRUE'在上面的数据框中用黄色突出显示或着色一个单词

这是我尝试过的代码:

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

我收到以下错误

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

我在这里做错了什么?

标签: pythonpandasdataframecolorshighlight

解决方案


改用:Styler.applymap_apply

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

您还可以通过Trueif boolean 和'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)

图片

如果还想删除索引值:

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

图1


推荐阅读