python - Pandas 样式 `.render()` - 显示前后的不同值

标签 python html pandas pandas-styles

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

输出结果:enter image description here

以下调用:
display_multi_table(tables, True)

输出结果:enter image description here

我的目标:无需调用 display 即可实现第二个屏幕截图底部的输出.

我尝试过/检查过的事情:
  • 如果我不设置 pandas 数据框的样式,只需调用 .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_displayFalse .

    关于python - Pandas 样式 `.render()` - 显示前后的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61567976/

    相关文章:

    Python future 警告 : The default dtype for empty Series will be 'object'

    python - 搜索一个数组中的特定元素并复制另一数组中的整个相应行

    python - Pandas 如何将时间戳列(EST)转换为其他列中可用的本地时区信息

    python - 有条件地替换 NaN

    html - Flexbox布局: how to set every item same width in multi rows?

    php - 如何将动态生成的图像保存到我的数据库中?

    html - CSS 默认边框颜色

    python - 改变 pandas 数据框的结构

    需要 Python 2.6 版,在注册表中找不到

    Python pandas 将绝对值加到一个系列中的正数/负数