如何根据使用to_html从pd.DataFrame生成的HTML表格的值更改颜色 [英] How do i change color based on value of an HTML table generated from a pd.DataFrame using to_html
本文介绍了如何根据使用to_html从pd.DataFrame生成的HTML表格的值更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 to_html()
转换为HTML表格的熊猫dataFrame,但是我想根据HTML表格中的值为某些单元格着色,返回。
任何想法如何去做这件事?
例如:名为'abc'的列中所有单元格的值大于5必须显示为红色,否则为蓝色。
解决方案
这是一种方法:
df = pd。 DataFrame(np.random.randint(0,10,(5,3)),columns = list('abc'))
def color_cell(cell):
return'color: '+('red'if cell> 5 else'green')
html = df.style.applymap(color_cell,subset = ['a'])。render()
with open('c:/temp/a.html','w')as f:
f.write(html)
结果:
I have a pandas dataFrame which I am converting to an HTML table using to_html()
however I would like to color certain cells based on values in the HTML table that I return.
Any idea how to go about this?
Eg: All cells in a column called 'abc' that have a value greater than 5 must appear red else blue.
解决方案
here is one way to do this:
df = pd.DataFrame(np.random.randint(0,10, (5,3)), columns=list('abc'))
def color_cell(cell):
return 'color: ' + ('red' if cell > 5 else 'green')
html = df.style.applymap(color_cell, subset=['a']).render()
with open('c:/temp/a.html', 'w') as f:
f.write(html)
result:
这篇关于如何根据使用to_html从pd.DataFrame生成的HTML表格的值更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文