【问题标题】:Adding image to pandas DataFrame将图像添加到熊猫 DataFrame
【发布时间】:2019-04-27 08:34:14
【问题描述】:

假设我有一个要导出为 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'] 

【问题讨论】:

  • 检查this - 显示图片的url链接。

标签: python pandas beautifulsoup


【解决方案1】:

您可能需要使用一些宽度和高度属性,但这应该可以帮助您入门。基本上,您只是将图像/链接转换为 html,然后使用 df.to_html 来显示这些标签。请注意,它不会显示您是否在 Spyder 中工作,但正如您在下面的输出中看到的那样,通过 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)))

然后你有一些选择去那里做什么去pdf。

你可以另存为html

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

然后只需使用 html 到 pdf 转换器here,或使用诸如pdfkitWeasyPrint 之类的库。我对这些并不完全熟悉(很久以前我只使用过一次),但这里有一个很好的link

祝你好运。

【讨论】:

  • 感谢@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))))。如图here
  • @chitown88 格式化程序在保存到 html 文件时丢失。 df.to_html('test_html.html', escape=False, formatters=dict(image=path_to_image_html))
  • 好问题。几个小时后我有机会坐在我的笔记本电脑前,我会更新这段代码。
  • @rom,好的,我更新了代码。它对您不起作用的原因是您需要为格式化程序使用字典。
  • 也有多种方法可以做到这一点。您只需将该功能单独应用于每一列,然后就不需要使用格式化程序参数
猜你喜欢
  • 1970-01-01
  • 2016-03-09
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
  • 2014-02-24
  • 2014-04-12
  • 2021-08-18
相关资源
最近更新 更多