5
$\begingroup$

I would like to display images (mostly jpg and png formats) directly from their url link inside a pandas dataframe. Imagine I already have the following dataframe:

id image_url
1  http://www.nstravel.ro/wp-content/uploads/2015/02/germany-profile_6023_600x450.jpg
2  https://www.nh-hotels.com/multimedia/images/cityscape-of-berlin_retoque_600x458-tcm41-132903-32.jpg
3  https://www.scandichotels.com/imagevault/publishedmedia/8q33xlshjl4o9d5ftp3r/germany-berlin-berliner-dom-cathedral-in-the-eveni.jpg

I would like to have the actual image displayed in another column (properly resized to fit).

I am aware that I could do it differently, e.g. not using pandas and go with grids using matplotlib, but for ease of illustration and presentation I would prefer to show it within a table (dataframe).

I have found these solutions: solution1, solution2. These suggested solutions while seem very relevant but did not work for me. Even I tried with images from my local disk, but I get this using the solution2:

enter image description here

Python: 3.6.5, Pandas: 0.23.0, Jupyter: 4.4.0

Thanks!

$\endgroup$
5
$\begingroup$

Actually the solution2 worked; I just had to be a bit more patient. I am posting it here in case someone have difficulties, like me, getting this to work:

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

def path_to_image_html(path):
    '''
     This function essentially convert the image url to 
     '<img src="'+ path + '"/>' format. And one can put any
     formatting adjustments to control the height, aspect ratio, size etc.
     within as in the below example. 
    '''

    return '<img src="'+ path + '" style=max-height:124px;"/>'

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

Note that df is your actual dataframe name, column_name_with_image_links is the column name that contains all image urls, and path_to_image_html is the above function.

| improve this answer | |
$\endgroup$
0
$\begingroup$

As an alternative to the above solution with formatters it is also possible to create a column with HTML img tag directly in the DataFrame. Another important note is that long URLs can be eaten by a string shortener (contents get replaced by ...). To avoid this one can use pd.option_context() with display.max_colwidth set an appropriate value.

The above mentioned is turned into something like:

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

df['img_html'] = df['column_name_with_image_links']\
    .str.replace(
        '(.*)', 
        '<img src="\\1" style="max-height:124px;"></img>'
    )
with pd.option_context('display.max_colwidth', 10000):
    HTML(df.to_html(escape=False))
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.