假设我有一个要导出为PDF的DataFrame。在DataFrame中,我有以下几列:代码,名称,价格,净额,销售额。每行都是一个产品。
我想向该DataFrame中的每个产品添加一个我可以使用BeautifulSoup获得的图像。 是否可以通过某种方式将图像添加到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']
答案 0 :(得分:4)
您可能需要稍微玩一下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)))
然后,您可以选择在其中做什么以转为pdf。
您可以另存为html
df.to_html('test_html.html', escape=False)
然后只需使用html到pdf转换器here,或使用pdfkit或WeasyPrint之类的库。我对它们并不完全熟悉(很久以前我只使用过其中一个),但这是一个不错的link
祝你好运。