Jose R
Jose R

Reputation: 950

Displaying Images stored within a dataframe in Jupyter Notebooks

Images in a dataframe are not displaying when using the display() function in Jupyter Notebooks. Here is my code which has the issue at the moment of displaying:

images = []

# Iterate through the rest of the molecules in the dataframe
for i in range(0, len(df)):
    mol = df.iloc[i]['Molecule']
    match = mol.GetSubstructMatch(ref_mol)
    img = Draw.MolToImage(mol, highlightAtoms=match)
    images.append(img)

# Add the images to the dataframe as a new column
df['Match_Image'] = images

# Display the resulting table
display(df)

I am expecting an image in the last column, instead I am getting PIL.PngImagePlugin.PngImageFile image mode=RG. in each of the cells where the images should be displayed.

Here is a screenshot of the display (last line of code and top of displayed table):

Expected output

What can I do to solve this issue ? I've already tried uninstalling Pillow and re-installing.

Upvotes: 0

Views: 916

Answers (1)

betelgeuse
betelgeuse

Reputation: 1266

You just need to re-format the PIL image objects a bit to display those images. Here's a sample code on how to do that:

import base64
from io import BytesIO

images = []

# Iterate through the rest of the molecules in the dataframe
for i in range(0, len(df)):
    mol = df.iloc[i]['Molecule']
    match = mol.GetSubstructMatch(ref_mol)

    img = Draw.MolToImage(mol, highlightAtoms=match)
    with BytesIO() as buffer:
        img.save(buffer, img.format)
        img_str = base64.b64encode(buffer.getvalue()).decode()
    images.append(f'<img src="data:image/{img.format};base64,{img_str}"/>')

# Add the images to the dataframe as a new column
df['Match_Image'] = images

# Display the resulting table
display(df)

If display(df) doesn't work, you may have to try

from IPython.display import HTML, display

display(HTML(df.to_html(escape=False)))

Upvotes: 2

Related Questions