我有一个像这样的数据框
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,并且之前使用过to_html
like
df.to_html(classes=['table', 'table-hover', 'table-bordered'],
float_format=lambda x: '{0:.3f}s'.format(x))
但后来我遇到了Style功能,并认为在我的 DataFrame 中为浮动提供一个样式器会很好。喜欢
def colorize(num)
color = 'red' if (np.isnan(num) or num > 0) else 'green'
return 'color: %s' % color
我可以将其应用于我的 DataFrame
df_styler = df.Style.applymap(colorize)
But now df_styler
is a Styler对象,虽然它有一个render
方法,我不知道如何通过classes
我使用的列表或浮动格式化程序to_html
不再...
有没有一种方法可以结合使用Style
函数和 CSS 类/格式化程序位于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)
Result:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)