Python 根据条件设置单元格颜色(在多索引中)

Python 根据条件设置单元格颜色(在多索引中),python,pandas,Python,Pandas,嗨,我想为特定元素设置颜色,并在数据框中编写excel/html 我的数据框是: old new diff query result query result result 1 q1 a1 q1 a1 True 2 q2 a2 q2 a5 False 3 q3 a3 q3 a3 True 4

嗨,我想为特定元素设置颜色,并在数据框中编写excel/html

我的数据框是:

  old                new            diff
  query result       query result   result
1 q1    a1           q1    a1       True
2 q2    a2           q2    a5       False
3 q3    a3           q3    a3       True
4 q4    a4           q4    a6       False
当我将此数据框写入excel/html时,我想突出显示['diff']['result']列中的假数据

如何突出显示单元格


谢谢

以下是您可以做的

def color_false_red(val):
    color = 'red' if val is False else 'black'
    return 'color: %s' % color
在你的df中

df.style.apply(color_false_red, subset=['diff'])

这将改变文本的颜色。

以下是您可以做的

def color_false_red(val):
    color = 'red' if val is False else 'black'
    return 'color: %s' % color
在你的df中

df.style.apply(color_false_red, subset=['diff'])
这将更改文本的颜色。

更改函数,使用和选择多索引列使用元组:

def coloring(val):
    color = 'red' if val is False else ''
    return 'color: %s' % color

df.style.applymap(coloring, subset=[('diff','result')])
更改函数,使用和选择多索引列使用元组:

def coloring(val):
    color = 'red' if val is False else ''
    return 'color: %s' % color

df.style.applymap(coloring, subset=[('diff','result')])

读这个:读这个:@sjpark-不客气!如果我的回答有帮助,别忘了。谢谢。有没有一个方法可以应用这个函数。要应用html方法?@sjpark-没有,但是如果想要呈现html只添加html=df.style.applymapcoloring,subset=['diff','result']。render@Ambleu-当然,将颜色更改为背景色如何将索引包含为子集?现在它可以在多页excel上工作了吗?@sjpark-不客气!如果我的回答有帮助,别忘了。谢谢。有没有一个方法可以应用这个函数。要应用html方法?@sjpark-没有,但是如果想要呈现html只添加html=df.style.applymapcoloring,subset=['diff','result']。render@Ambleu-当然,将颜色更改为背景色如何将索引包含为子集?现在它在多页excel上工作吗?