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

旧巷老猫 提交于 2019-12-12 08:05:50

问题


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?

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.

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

Is there any solution for this?

Thanks for your help.


回答1:


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 "...".

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:


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.

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



回答3:


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.



来源:https://stackoverflow.com/questions/37365824/pandas-ipython-notebook-include-and-display-an-image-in-a-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!