Pandas HTML 输出条件格式 - 如果值在范围内,则突出显示单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37638402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:20:20  来源:igfitidea点击:

Pandas HTML Output Conditional Formatting - Highlight cell if value in range

htmlpandasformattingconditional

提问by Felix

I am building report in HTML format using pd.to_html() method. Can anyone clarify how can i format cells with values between -0.5 and 0.5 with green back ground for particular columns of data frame?

我正在使用 pd.to_html() 方法以 HTML 格式构建报告。任何人都可以澄清如何为数据框的特定列设置具有绿色背景的 -0.5 和 0.5 之间的值的单元格格式?

回答by joris

You can do custom formatting of DataFrames using the styleattribute (introduced starting from pandas v0.17.1). An example to do what you want:

您可以使用style属性(从 pandas v0.17.1 开始引入)对 DataFrame 进行自定义格式设置。做你想做的一个例子:

df = pd.DataFrame(np.random.randn(5,5), columns=list('ABCDE'))

def highlight_vals(val, min=-0.5, max=0.5, color='green'):
    if min < val < max:
        return 'background-color: %s' % color
    else:
        return ''

df.style.applymap(highlight_vals, subset=['B', 'C', 'D'])

gives you

给你

enter image description here

在此处输入图片说明

See this notebook for the full example: http://nbviewer.jupyter.org/gist/jorisvandenbossche/8b74f71734cd6d75a58c5a048261a7a7

有关完整示例,请参阅此笔记本:http: //nbviewer.jupyter.org/gist/jorisvandenbossche/8b74f71734cd6d75a58c5a048261a7a7

And see the docs for more example how to format the dataframe: http://pandas.pydata.org/pandas-docs/stable/style.html

有关如何格式化数据框的更多示例,请参阅文档:http: //pandas.pydata.org/pandas-docs/stable/style.html

To write the output to a file, you can do:

要将输出写入文件,您可以执行以下操作:

with open('filename.html', 'w') as f:
    f.write(df.style.applymap(highlight_vals, subset=['B', 'C', 'D'])
                    .set_table_attributes("border=1").render())