向pandas DataFrame添加图像

18

假设我有一个DataFrame想要导出到PDF中。在这个DataFrame中,我有以下列:Code、Name、Price、Net、Sales。每行都是一个产品。

我想要为数据中的每个产品添加一张图像,可以通过BeautifulSoup获取。有没有什么办法将该图像添加到DataFrame中?不是链接,而是产品的图像。

更具体地说,我想要像这样:

enter image description here

Code:

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

#Suppose this are the links that contains the imagen i want to add to the DataFrame
images = ['Link 1','Link 2'] 

1
查看此链接 - 显示图片的网址链接。 - jezrael
1个回答

34

你可能需要稍微调整宽度和高度属性,但这应该可以让你开始。基本上,你只需将图像/链接转换为html,然后使用df.to_html来显示这些标记。请注意,如果你正在使用PyCharm、Spyder等IDE工作,它不会显示出来,但正如你可以在下面看到我的输出一样,通过jupyter笔记本可以正常工作。

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

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

# your images
images1 = ['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'] 


images2 = ['https://static3.srcdn.com/wordpress/wp-content/uploads/2020/07/Quidditch.jpg?q=50&fit=crop&w=960&h=500&dpr=1.5',
           'https://specials-images.forbesimg.com/imageserve/5e160edc9318b800069388e8/960x0.jpg?fit=scale']

df['imageUrls'] = images1
df['otherImageUrls'] = images2


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

pd.set_option('display.max_colwidth', None)

image_cols = ['imageUrls', 'otherImageUrls']  #<- define which columns will be used to convert to html

# Create the dictionariy to be passed as formatters
format_dict = {}
for image_col in image_cols:
    format_dict[image_col] = path_to_image_html


display(HTML(df.to_html(escape=False ,formatters=format_dict)))

Output

然后你有一些选项可以将其转换为pdf。

你可以保存为html。

df.to_html('test_html.html', escape=False, formatters=format_dict)

那么只需使用 HTML 转 PDF 工具 这里,或者使用类库例如 pdfkitWeasyPrint。我对它们并不是完全熟悉(只有很久以前用过其中一种),但这是一个不错的链接

祝好运。


1
感谢您的出色回答,@chitown88,这正是我所需要的。代码只需要稍作更新。将 from IPython.core.display import HTML 更改为 from IPython.core.display import display, HTML,并将 HTML(df.to_html(escape=False ,formatters=dict(image=path_to_image_html))) 更改为 display(HTML(df.to_html(escape=False ,formatters=dict(image=path_to_image_html)))))。如此所示在这里 - Rens
你如何将格式应用于多列?我有一个包含两列图像URL的数据框,想要呈现这些图像,但是formatters=[path_to_image_html("imageUrls"), path_to_image_html("otherImageUrls")]没有起作用。 - rom
1
好问题。我会在几个小时后有机会坐在笔记本电脑前时更新这段代码。 - chitown88
1
@rom,好的,我更新了代码。它对你不起作用的原因是你需要使用一个字典来进行格式化。 - chitown88
1
这个可以有多种方法来实现。你可以将该函数分别应用于每一列,这样就不需要使用格式化参数了。 - chitown88
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接