pythonpandasdataframe

How to map images to a Pandas Dataframe from a Dictionary


This question helped a lot with what I am trying to do. I now know how to insert images to a pandas dataframe, but now I want to figure out how to do it with a dictionary. For example, I have the following df

  Name Team
0  A    ARI
1  B    BAL
2  C    ATL

I also have the following dictionary where the keys match the Team field.

images = {
'ARI':'https://upload.wikimedia.org/wikipedia/en/thumb/7/72/Arizona_Cardinals_logo.svg/179px-Arizona_Cardinals_logo.svg.png',
'ATL':'https://upload.wikimedia.org/wikipedia/en/thumb/c/c5/Atlanta_Falcons_logo.svg/192px-Atlanta_Falcons_logo.svg.png',
'BAL':'https://upload.wikimedia.org/wikipedia/en/thumb/1/16/Baltimore_Ravens_logo.svg/193px-Baltimore_Ravens_logo.svg.png'
}

I am wondering how to alter the following code from the question I linked so that I can display the the correct picture according to the value in the Team field.

import pandas as pd
from IPython.core.display import HTML

df = pd.DataFrame([['A231', 'Book', 5, 3, 150], 
                   ['M441', 'Magic Staff', 10, 7, 200]],
                   columns = ['Code', 'Name', 'Price', 'Net', 'Sales'])

# your images
images = ['https://vignette.wikia.nocookie.net/2007scape/images/7/7a/Mage%27s_book_detail.png/revision/latest?cb=20180310083825',
          'https://i.pinimg.com/originals/d9/5c/9b/d95c9ba809aa9dd4cb519a225af40f2b.png'] 


df['image'] = images

# convert your links to html tags 
def path_to_image_html(path):
    return '<img src="'+ path + '" width="60" >'

pd.set_option('display.max_colwidth', -1)

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

Thank you for the help in advance.


Solution

  • import pandas as pd
    from IPython.display import HTML
    
    df = pd.DataFrame({'name': ['A', 'B', 'C'], 'team': ['ARI', 'BAL', 'ATL']})
    
    # given the images in a dict
    images = {'ARI':'https://upload.wikimedia.org/wikipedia/en/thumb/7/72/Arizona_Cardinals_logo.svg/179px-Arizona_Cardinals_logo.svg.png',
              'ATL':'https://upload.wikimedia.org/wikipedia/en/thumb/c/c5/Atlanta_Falcons_logo.svg/192px-Atlanta_Falcons_logo.svg.png',
              'BAL':'https://upload.wikimedia.org/wikipedia/en/thumb/1/16/Baltimore_Ravens_logo.svg/193px-Baltimore_Ravens_logo.svg.png'}
    
    # map images to team, base on keys
    df['image'] = df.team.map(images)
    
    # convert your links to html tags 
    def path_to_image_html(path):
        return '<img src="'+ path + '" width="60" >'
    
    HTML(df.to_html(escape=False, formatters=dict(image=path_to_image_html)))
    

    enter image description here