Skip to main content
 首页 » 编程设计

python之将图像添加到 pandas DataFrame

2025年05月04日11zhwl

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

我想向该 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']  

请您参考如下方法:

您可能需要尝试一下宽度和高度属性,但这应该能让您入门。基本上,您只是将图像/链接转换为 html,然后使用 df.to_html 来显示这些标签。请注意,它不会显示你是否在像 PyCharm、Spyder 这样的 IDE 中工作,但正如你在下面看到的我的输出,通过 jupyter notebooks 可以正常工作

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

然后您可以选择如何转到 pdf。

你可以保存为html

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

然后简单地使用 html 到 pdf 转换器 here ,或使用诸如 pdfkit 之类的库或 WeasyPrint .我对这些并不完全熟悉(很久以前我只用过其中一个),但这里有一个很好的 link

祝你好运。