Pandas / IPython Notebook:在数据框中包含和显示图像

Posted

技术标签:

【中文标题】Pandas / IPython Notebook:在数据框中包含和显示图像【英文标题】:Pandas / IPython Notebook: Include and display an Image in a dataframe 【发布时间】:2016-09-18 20:21:50 【问题描述】:

我有一个 pandas 数据框,它还有一个带有图像文件名的列。如何在 DataFrame 中显示图像?

我尝试了以下方法:

import pandas as pd
from IPython.display import Image

df = pd.DataFrame(['./image01.png', './image02.png'], columns = ['Image'])

df['Image'] = Image(df['Image'])

但是当我显示框架时,每一列只显示图像对象的 to_string 表示。

    Image
0   IPython.core.display.Image object
1   IPython.core.display.Image object

有什么解决办法吗?

感谢您的帮助。

【问题讨论】:

【参考方案1】:

我建议使用格式化程序,而不是将 html 代码插入数据框。不幸的是,您需要设置截断设置,因此长文本不会被“...”截断。

import pandas as pd
from IPython.display import Image, HTML

df = pd.DataFrame(['./image01.png', './image02.png'], columns = ['Image'])

def path_to_image_html(path):
    return '<img src="'+ path + '"/>'

pd.set_option('display.max_colwidth', -1)

HTML(df.to_html(escape=False ,formatters=dict(Image=path_to_image_html)))

【讨论】:

【参考方案2】:

我找到的解决方案是不使用 IPython.display Image,而是使用 IPython.display HTML 和数据框的 to_html(escape=False) 功能。

总而言之,它看起来像这样:

import pandas as pd
from IPython.display import Image, HTML

df = pd.DataFrame(['<img src="image01.png"/>', './image02.png'], columns = ['Image'])

HTML(df.to_html(escape=False))

【讨论】:

【参考方案3】:

我认为您误解了数据框中存储的内容,并将其与显示方式混淆了。为了在 html 表格表示中显示图像,您必须编写自己的函数以在 html 表格单元格中插入图像标记。

【讨论】:

以上是关于Pandas / IPython Notebook:在数据框中包含和显示图像的主要内容,如果未能解决你的问题,请参考以下文章

在 IPython Notebook 中显示所有 pandas 数据框

Pandas / IPython Notebook:在数据框中包含和显示图像

ipython notebook pandas max 允许的列数

InstagramAPI - 如何将 JSON Python 数据解析为 Pandas DataFrame(iPython、Jupyter Notebook)

在IPython Notebook中愉快地使用python编程

IPython Notebook 中的“斑马表”?