如何将“style”与数据帧上的“to_html”类结合使用?

2024-05-17 01:25:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框

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))

但后来我遇到了Style特性,并认为在我的数据帧中有一个float的样式器会很好。就像

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是一个^{}对象,虽然它有一个render方法,但是我不知道如何传递与to_html一起使用的classes列表或浮点格式化程序。。。

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


Tags: to数据方法formatdfstylehtmlnp
1条回答
网友
1楼 · 发布于 2024-05-17 01:25:25

试试这个:

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)

结果:

enter image description here

相关问题 更多 >