pandas 如何将`style` 与DataFrame 上的`to_html` 类结合使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42629171/
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
How to use `style` in conjunction with the `to_html` classes on a DataFrame?
提问by Eric Hansen
I have a DataFrame like
我有一个像
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
I am trying to output this DataFrame as HTML, and was previously using to_html
like
我正在尝试将此 DataFrame 输出为 HTML,并且以前使用过to_html
类似
df.to_html(classes=['table', 'table-hover', 'table-bordered'],
float_format=lambda x: '{0:.3f}s'.format(x))
But then I came across the Stylefeature, and thought that it would be nice to have a styler for the floats in my DataFrame. Like
但是后来我遇到了Style功能,并认为在我的 DataFrame 中为浮点数设置一个样式器会很好。喜欢
def colorize(num)
color = 'red' if (np.isnan(num) or num > 0) else 'green'
return 'color: %s' % color
which I can apply to my DataFrame with
我可以将其应用于我的 DataFrame
df_styler = df.Style.applymap(colorize)
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...
但是现在df_styler
是一个Styler
对象,虽然它有一个render
方法,但我不知道如何传递classes
我to_html
再使用的列表或浮点格式化程序......
Is there a way that I can combine using Style
functions and the CSS classes / formatters found in to_html
?
有没有一种方法可以组合使用Style
函数和 .css 中的 CSS 类/格式化程序to_html
?