You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter Notebook调用display时Pandas DataFrame不渲染单元格内HTML问题

问题解决方法

根因定位

  • 你在单元格末尾直接返回df.style.set_table_styles()生成的Styler对象时,Jupyter会自动识别Pandas Styler类型,触发内置的HTML渲染逻辑,不会转义单元格内的HTML内容,因此可以正常显示矩阵。
  • 你调用display(df)时,展示的是普通的DataFrame对象,该对象的单元格内存储的是纯HTML字符串,普通DataFrame的默认展示逻辑会转义所有HTML标签,因此只会输出原始HTML源码,不会渲染为可视化矩阵。

解决方案

你不需要展示原始DataFrame,而是将构建好的Styler对象传入display函数即可,修改后的代码如下:

import pandas as pd
data = [
    [[1]],
    [[1.0,2.0],[2.0,4.0],[8.0,3.0],[9.0,7.0]],
    [[0.487],[1.532],[1.544],[1.846]],
    [[3.0]],
    [[3.0]],
    [[-1]],
]
    
df = pd.DataFrame([
    [(pd.DataFrame(x)
        .style
        .hide_index()
        .hide_columns()
        .set_table_attributes('class="matrix"')
        .to_html()
     ) for x in data]
], dtype="object")
# 先把Styler对象存下来
styler = df.style.set_table_styles([
    {"selector": ".matrix", "props": "position: relative;"},
    {"selector": ".matrix:before, .matrix:after", 
     "props":  'content: ""; position: absolute; top: 0; border: 1px solid #000; width: 6px; height: 100%;'
    },
    {"selector": ".matrix:before", "props": "left: -0px; border-right: -0;"},
    {"selector": ".matrix:after", "props": "right: -0px; border-left: 0;"}
])
# 直接展示Styler对象,不要展示原始df
display(styler)

备用方案

如果上述方法依然无法正常渲染,可以主动读取Styler的HTML内容,用IPython的HTML渲染组件展示:

from IPython.display import HTML
display(HTML(styler.to_html()))

内容的提问来源于stack exchange,提问作者Mohammad Badri Ahmadi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:12:03