首页 > 解决方案 > Pandas 样式`.render()` - 显示前后不同的值

问题描述

我试图在 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.

我尝试过/检查过的事情:

标签: pythonhtmlpandaspandas-styles

解决方案


尝试将您的 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_displayFalse


推荐阅读