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

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

我在这里做错了什么?
2个回答

2
请使用 Styler.applymap 代替 apply:
dataframe.style.\
       applymap(color_negative_red).\
       to_excel('df.xlsx')

您还可以通过 True(布尔类型)或 'True'(字符串类型)进行比较:
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)

pic1


如果我们处理的是ndarray而不是Series或DataFrame呢? - Ash

1
尝试这个(这里可以使用apply):
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)

1
使用先前的代码(具有applymap),无论是'True'还是'FALSE',背景颜色都会变为黑色。 - pytorch
@pytorch 修改了注释,现在怎么样? - U13-Forward

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接