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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37365824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:16:02  来源:igfitidea点击:

Pandas / IPython Notebook: Include and display an Image in a dataframe

pythonpandasipythonjupyter-notebook

提问by Regenschein

I have a pandas Dataframe which also has a column with a filename of an image. How can I display the image inside of the DataFrame?

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

I tried the following:

我尝试了以下方法:

import pandas as pd
from IPython.display import Image

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

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

But when I show the frame, each column only shows the to_string representation of the Image Object.

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

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

Is there any solution for this?

有什么解决办法吗?

Thanks for your help.

谢谢你的帮助。

回答by Fabian Hertwig

Instead of inserting the html code into the dataframe, I suggest to use a formatter. Unfortunately you need to set the truncation settings, so long text doesn't get truncated with "...".

我建议使用格式化程序,而不是将 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)))

回答by Regenschein

The solution I found is to not use the IPython.display Image, but to use the IPython.display HTML and the to_html(escape=False) feature of a dataframe.

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

Altogether, it looks like this:

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

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))

回答by piRSquared

I think you are misunderstanding what gets stored in a dataframe and confusing it with how it's displayed. In order to show an image in the html table representation you'd have to write your own function to insert an image tag in the html table cell.

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