我试图在 Jupyter 笔记本中水平显示几个 pandas 数据帧,但遇到了样式器的 HTML 格式不正确的情况。
我有以下代码片段:
import numpy as np
import pandas as pd
from IPython.display import display, HTML
def display_multi_table(table_list, with_display):
if with_display:
for t in table_list: display(t)
return HTML(
'<table><tr style="background-color:white;">' +
''.join(['<td style="height:300px;width:300px">' + table.render() + '</td>' for table in table_list]) +
'</tr></table>'
)
d = dict([(f"column_{i}", np.random.rand(5)) for i in range(3)])
tables = [pd.DataFrame(d).style.set_caption("Title") for i in range(3)]
以下调用:
display_multi_table(tables, False)
输出结果:
以下调用:
display_multi_table(tables, True)
输出结果:
我的目标:无需调用
display
即可实现第二个屏幕截图底部的输出.我尝试过/检查过的事情:
.to_html()
在数据帧上而不是调用 .render()
在样式器上,这个问题不存在。但是,我需要它来处理样式数据框。 table.render()
返回的值调用 display
前后确实不一样。 最佳答案
尝试将您的 html 传递到显示中,而不是分别在每个表上调用 display():
import numpy as np
import pandas as pd
from IPython.display import display, HTML
def display_multi_table(table_list, with_display):
html = HTML(
'<table><tr style="background-color:white;">' +
''.join(['<td style="height:300px;width:300px">' + table.render() + '</td>' for table in table_list]) +
'</tr></table>'
)
if with_display:
display(html)
return html
请注意,如果您调用
display_multi_table(tables, True)
在 jupyter 单元格的末尾,不将其设置为等于任何值,它将有效地显示表格两次 - 一次来自 display(html)
, 一次来自函数的返回值 (return html
)。如果这是不希望的行为,则只需将函数调用设置为等于变量 (html = display_multi_table(tables, True)
),或设置 with_display
至False
.
关于python - Pandas 样式 `.render()` - 显示前后的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61567976/