如何在DataFrame上将`style`与`to_html`类结合使用? [英] How to use `style` in conjunction with the `to_html` classes on a DataFrame?
问题描述
我有一个类似
df = pd.DataFrame(np.random.randn(10).reshape(2, 5))
df
# 0 1 2 3 4
# 0 -0.067162 -0.505401 -0.019208 1.123936 0.087682
# 1 -0.373212 -0.598412 0.185211 0.736143 -0.469111
我正在尝试将此DataFrame输出为HTML,并且以前使用
I am trying to output this DataFrame as HTML, and was previously using to_html
like
df.to_html(classes=['table', 'table-hover', 'table-bordered'],
float_format=lambda x: '{0:.3f}s'.format(x))
但是后来我遇到了样式功能,并认为在我的DataFrame中为float设置样式器会很好.喜欢
But then I came across the Style feature, and thought that it would be nice to have a styler for the floats in my DataFrame. Like
def colorize(num)
color = 'red' if (np.isnan(num) or num > 0) else 'green'
return 'color: %s' % color
我可以使用
df_styler = df.Style.applymap(colorize)
但是现在df_styler
是 Styler
对象,尽管它具有render
方法,但我看不到如何传递与to_html
一起使用的classes
列表或float格式化程序...
But now df_styler
is a Styler
object, and though it has a render
method, I don't see how I can pass the classes
list or float formatter which I was using with to_html
anymore...
有没有一种方法可以结合使用Style
函数和to_html
中的CSS类/格式化程序?
Is there a way that I can combine using Style
functions and the CSS classes / formatters found in to_html
?
推荐答案
尝试一下:
html = df.style.applymap(colorize) \
.set_table_attributes('border="1" class="dataframe table table-hover table-bordered"') \
.set_precision(3) \
.render()
with open('d:/temp/a2.html', 'w') as f:
f.write(html)
结果:
这篇关于如何在DataFrame上将`style`与`to_html`类结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!