Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I want to figure out how to insert the image into the 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':'',

'ATL':'',

'BAL':''

}

I am wondering how to alter the code from displaying 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 = ['/revision/latest?cb=20180310083825',

          ''] 

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)))

1 Answer

0 votes
by (36.8k points)

Use the pandas.Series.map to map the images to the 'team'

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':'',

          'ATL':'',

          'BAL':''}

# 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)))

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

Related questions

Browse Categories

...