将图像添加到熊猫DataFrame

Sne*_*cor 1 python beautifulsoup pandas

假设我有一个要导出为PDF的DataFrame。在DataFrame中,我有以下几列:代码,名称,价格,净额,销售额。每行都是一个产品。

我想将可以使用BeautifulSoup获得的图像添加到该DataFrame中的每个产品。有什么方法可以将图像添加到DataFrame吗?不是链接,只是产品的图像。

具体来说,我想要这样的事情:

在此处输入图片说明

码:

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'] 
Run Code Online (Sandbox Code Playgroud)

chi*_*n88 8

您可能需要稍微玩一下width和height属性,但这应该可以帮助您入门。基本上,您只是将图像/链接转换为html,然后使用df.to_html显示这些标签。请注意,它不会显示您是否在Spyder中工作,但是如下面的我的输出所示,通过jupyter笔记本可以正常工作

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)))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

然后,您可以选择在该处做什么以转至pdf。

您可以另存为html

df.to_html('test_html.html', escape=False)
Run Code Online (Sandbox Code Playgroud)

然后只需在此处使用和html到pdf转换器,或使用pdfkitWeasyPrint之类的库。我并不完全熟悉这些(很久以前我只使用过其中一个),但这是一个很好的链接

祝好运。