How to Add Image to Pandas Dataframe

Fariba Laiq Feb 02, 2024
How to Add Image to Pandas Dataframe

Sometimes we want to create a pandas dataframe that consists of images. We can achieve this task using the HTML module in Python Pandas.

We will convert the path of the image to an HTML tag. Then, convert the dataframe to an HTML table and display the image. Python has a built-in module called HTML. We can encode and decode HTML in Python.

Use HTML Module to Render Image in a Pandas DataFrame

In the following code, we have created a dataframe containing the information about the artist and the painting title. To display the images in this dataframe, we will make a list containing the paths of the images.

We will assign this list to the dataframe as a column. We have created a function that converts the path to the HTML’s img tag by concatenating <img src= with the path.

The function also resizes the image to a small scale using the width attribute. Then we have converted the pandas dataframe to an HTML table using the to_html() method.

We called the HTML method to render the images. Lastly, we displayed the whole dataframe using the display() method.

Example Code:

# Python 3.x
import pandas as pd
from IPython.core.display import HTML

df = pd.DataFrame(
    [
        ["Van Gogh", "Starry Night"],
        ["Van Gogh", "Sunflowers"],
        ["Van Gogh", "Cafe Terrace at Night"],
    ],
    columns=["Artist", "Painting Title"],
)
painting_images = [
    "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/1200px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg",
    "https://iiif.micr.io/TZCqF/full/1280,/0/default.jpg",
    "https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Vincent_Willem_van_Gogh_-_Cafe_Terrace_at_Night_%28Yorck%29.jpg/816px-Vincent_Willem_van_Gogh_-_Cafe_Terrace_at_Night_%28Yorck%29.jpg",
]
df["Painting"] = painting_images


def to_img_tag(path):
    return '<img src="' + path + '" width="50" >'


display(HTML(df.to_html(escape=False, formatters=dict(Painting=to_img_tag))))

Output:

add image in pandas dataframe

Author: Fariba Laiq
Fariba Laiq avatar Fariba Laiq avatar

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

LinkedIn

Related Article - Pandas DataFrame