将图像添加到 Pandas 数据框
Fariba Laiq
2024年2月15日
Pandas
Pandas DataFrame
![将图像添加到 Pandas 数据框](/img/Python-Pandas/feature-image---add-image-to-pandas-dataframe.webp)
有时我们想创建一个由图像组成的 pandas 数据框。我们可以使用 Python Pandas 中的 HTML 模块来完成这项任务。
我们将图像的路径转换为 HTML 标签
。然后,将数据框转换为 HTML 表格并显示图像。Python 有一个名为 HTML
的内置模块。我们可以在 Python 中编码和解码 HTML。
使用 HTML 模块在 Pandas DataFrame 中渲染图像
在以下代码中,我们创建了一个数据框,其中包含有关艺术家和绘画标题的信息。为了在这个数据框中显示图像,我们将创建一个包含图像的路径
的列表。
我们将此列表作为列分配给数据框。我们创建了一个函数,通过将 <img src=
与 path
连接起来,将路径转换为 HTML 的 img
标签。
该函数还使用宽度属性将图像调整为小比例。然后我们使用 to_html()
方法将 pandas 数据框转换为 HTML 表格。
我们调用 HTML 方法来渲染图像。最后,我们使用 display()
方法显示整个数据框。
示例代码:
# Python 3.x
import pandas as pd
from IPython.core.display import HTML
df = pd.DataFrame(
[
["Van Gogh", "Starry Night"],
["Van Gogh", "Sunflowers"],
["Van Gogh", "Cafe Terrace at Night"],
],
columns=["Artist", "Painting Title"],
)
painting_images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/1200px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg",
"https://iiif.micr.io/TZCqF/full/1280,/0/default.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Vincent_Willem_van_Gogh_-_Cafe_Terrace_at_Night_%28Yorck%29.jpg/816px-Vincent_Willem_van_Gogh_-_Cafe_Terrace_at_Night_%28Yorck%29.jpg",
]
df["Painting"] = painting_images
def to_img_tag(path):
return '<img src="' + path + '" width="50" >'
display(HTML(df.to_html(escape=False, formatters=dict(Painting=to_img_tag))))
输出:
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Fariba Laiq
I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.
LinkedIn