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

如何在Jupyter中封装展示格式化代码,实现DataFrame与图片并排展示

封装并排展示DataFrame与图片工具的实现方法

步骤1:创建独立工具模块

新建一个后缀为.py的文件,比如命名为jupyter_display_tools.py,将以下代码写入该文件:

import ipywidgets as widgets
from IPython import display
from IPython.display import HTML, Image

def display_df_img_side_by_side(df, img_path, img_width=1050, border_style='1px solid black'):
    # 初始化两个输出组件
    df_output = widgets.Output(layout={'border': border_style})
    img_output = widgets.Output(layout={'border': border_style})
    
    # 分别写入展示内容
    with df_output:
        display.display(HTML(df.to_html(index=False)))
    with img_output:
        display.display(Image(filename=img_path, width=img_width))
    
    # 横向排列组件并返回渲染对象
    return widgets.HBox([df_output, img_output])

各参数说明:

  • df:需要展示的Pandas DataFrame对象
  • img_path:待展示图片的本地存储路径
  • img_width:可选参数,控制图片展示宽度,默认值为1050
  • border_style:可选参数,控制组件边框样式,默认值为1px黑边

步骤2:Jupyter Notebook中调用

把刚才创建的.py文件放在你运行的Notebook同级目录下,在单元格中执行以下代码即可调用:

# 导入封装好的工具函数
from jupyter_display_tools import display_df_img_side_by_side

# 直接传入参数即可生成并排展示效果
display_df_img_side_by_side(你的DataFrame变量, '你的图片路径.png')

如果需要自定义参数,比如调整图片宽度为800、取消边框:

display_df_img_side_by_side(你的DataFrame变量, '你的图片路径.png', img_width=800, border_style='none')

内容的提问来源于stack exchange,提问作者Robert Altena

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:36:08