将图像添加到Pandas DataFrame [英] Adding image to pandas DataFrame

查看:107
本文介绍了将图像添加到Pandas DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a DataFrame I want to export to a PDF. In the DataFrame I have the following columns: Code, Name, Price, Net, Sales. Every row is a Product.

我想向该DataFrame中的每个产品添加一个我可以使用BeautifulSoup获得的图像. 是否可以通过某种方式将图像添加到DataFrame中??不是链接,只是产品的图像.

I want to add to every product in that DataFrame an image which i could get using BeautifulSoup. Is there some way to add the image to the DataFrame? Not the link, just the image of the product.

更具体地讲,我想要这样的东西:

Being more specific i want something like this:

代码:

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'] 

推荐答案

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

You'll probably have to play a bit around with width and height attributes, but this should get you started. Basically, you're just converting the image/links to html, then using the df.to_html to display those tags. Note, it won't show if you're working in Spyder, but as you can see below with my output, works fine through jupyter notebooks

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.

Then you have some options of what to do there to go to pdf.

您可以另存为html

You could save as html

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

然后只需在此处使用html到pdf转换器,或使用 WeasyPrint .我并不完全熟悉它们(很久以前我只使用过其中一个),但是这里有一个很好的

then simply use and html to pdf converter here, or use a library such as pdfkit or WeasyPrint. I'm not entirely familiar with those (I only used one of them once a long time ago), but here's a good link

祝你好运.

这篇关于将图像添加到Pandas DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆