9

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.

4 Answers 4

16

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 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={'Image': path_to_image_html}))
Sign up to request clarification or add additional context in comments.

Comments

10

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

Comments

0

A few times in the past I needed the ability to render elements in dataframes. Because of that I developed the package pandas-render. I'm the developer of this package and want to share this alternative approach.

  1. Install the package with: pip install pandas-render

  2. Create and render the dataframe:

    from pandas_render import pandas as pd
    
    df = pd.DataFrame(['./image01.png', './image02.png'], columns=['Image'])
    
    df.render({"Image": '<img src="{{ content }}"/>'}, n=5)
    

The parameter n allows to display n elements in a row. The result is a compact gallery of images.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.