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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:07:35  来源:igfitidea点击:

How to use `style` in conjunction with the `to_html` classes on a DataFrame?

pythonpandas

提问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_htmllike

我正在尝试将此 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_styleris a Stylerobject, and though it has a rendermethod, I don't see how I can pass the classeslist or float formatter which I was using with to_htmlanymore...

但是现在df_styler是一个Styler对象,虽然它有一个render方法,但我不知道如何传递classesto_html再使用的列表或浮点格式化程序......

Is there a way that I can combine using Stylefunctions and the CSS classes / formatters found in to_html?

有没有一种方法可以组合使用Style函数和 .css 中的 CSS 类/格式化程序to_html

回答by MaxU

Try this:

尝试这个:

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:

结果:

enter image description here

在此处输入图片说明