Python 如何在数据框中使用不同的颜色为布尔值着色

Python 如何在数据框中使用不同的颜色为布尔值着色,python,pandas,dataframe,colors,highlight,Python,Pandas,Dataframe,Colors,Highlight,我想在上面的数据框中突出显示一个单词“TRUE”,或将其涂成黄色 以下是我尝试过的代码: 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

我想在上面的数据框中突出显示一个单词
“TRUE”
,或将其涂成黄色

以下是我尝试过的代码:

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
我得到了下面的错误

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')
dataframe.style.\
       applymap(color_negative_red).\
       to_excel('df.xlsx', index=False)
您还可以通过
True
if布尔值和
'True'
if字符串进行比较:

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

如果还需要删除索引值:

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)

试试这个(在这里你可以使用
应用
):


使用前面的代码,无论是“真”还是“假”,背景色都变为黑色applymap@pytorch编辑的评论,那么现在呢?
def f(x):
    df = x.copy()
    for i in df.columns:
        df.loc[df[i]=='TRUE',i]=='background-color: yellow'
    return df    

df=df.style.apply(f, axis=None)