如何在DataFrame上将`style`与`to_html`类结合使用?

发布于 2021-01-29 15:58:52

我有一个像

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

我想输出这些数据帧为HTML,和以前使用to_html

df.to_html(classes=['table', 'table-hover', 'table-bordered'], 
           float_format=lambda x: '{0:.3f}s'.format(x))

但是后来我遇到了样式功能,并认为在我的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)

但是现在df_styler是一个Styler对象,尽管它有一个render方法,但我看不到如何传递classes我以前使用的列表或浮点格式化程序to_html

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

关注者
0
被浏览
183
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    尝试这个:

    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)
    

    结果:

    在此处输入图片说明



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看