pandas HTML输出条件格式 - 如果值在范围内,则突出显示单元格 [英] Pandas HTML Output Conditional Formatting - Highlight cell if value in range
问题描述
我使用pd.to_html()方法构建HTML格式的报告。任何人都可以澄清如何格式化数值在-0.5和0.5之间的数值与特定列的数据框的绿色背景?
解决方案您可以使用样式
属性(从pandas v0.17.1开始引入)自定义DataFrame的格式。
一个例子来做你想做的事:
pre $ d $ = 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'])
给你
完整示例请参阅本笔记本: http://nbviewer.jupyter.org/gist/jorisvandenbossche/8b74f71734cd6d75a58c5a048261a7a7
请参阅文档以获取更多示例如何格式化数据框: http:/ /pandas.pydata.org/pandas-docs/stable/style.html
要将输出写入文件,您可以这样做:
with open('filename.html','w )作为f:
f.write(df.style.applymap(highlight_vals,subset = ['B','C','D'])
.set_table_attributes(border = 1)。 render())
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?
You can do custom formatting of DataFrames using the style
attribute (introduced starting from pandas v0.17.1).
An example to do what you want:
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
See this notebook for the full example: 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
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())
这篇关于 pandas HTML输出条件格式 - 如果值在范围内,则突出显示单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!