python - 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
.
我尝试过/检查过的事情:
- 如果我不设置 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_display
为False
。
推荐阅读
- javascript - 如果函数在数组内部或外部,如何在重写 JSON.stringify 时使用递归并返回不同的值?
- amazon-web-services - 有没有办法以编程方式在其他区域创建别名提供程序和 AWS 资源?
- javascript - 有条件地在多选下拉列表中更改颜色
- javascript - Firebase Admin SDK 未按预期更新密码
- html - 为什么
元素改变它的高度? - php - 注销后尝试将用户发送到主页
- android - MotionLayout 与触摸区域块 RecyclerView
- python - TypeError:不可排序的类型:元组()> int()
- node.js - 如何正确调试 node.js 中的简单承诺?
- docker - Docker 在 Jenkins 中使用 apt-get install 构建问题