0

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.

1
  • Since this got a score of 0 here, I'd just like to let you know that MMSE has an rdkit tag and your question would probably be better received there. You can ask future questions there if you want, and if you want this question migrated you can ping me by typing @NikeDattani and I'll flag it for migration. Commented Feb 24, 2023 at 16:16

1 Answer 1

2

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)))
Sign up to request clarification or add additional context in comments.

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.