Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 256
Regenschein Avatar asked May 21 '16 17:05

Regenschein


People also ask

How do you display an image in a data frame?

Assign the country list to the existing dataframe df . This would be appended as a new column to the existing dataframe. Write a function that will convert the given path of the images to the HTML tag. Render the dataframe as an HTML table, and then call the HTML method to display the rendered images.

Can you store an image in a pandas Dataframe?

It is possible to wrap the images in a python list. That makes it possible to store it in a pandas DataFrame.


2 Answers

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)))
like image 186
Fabian Hertwig Avatar answered Oct 20 '22 07:10

Fabian Hertwig


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))
like image 10
Regenschein Avatar answered Oct 20 '22 08:10

Regenschein