首页 > 解决方案 > 熊猫数据框 to_html 格式化程序 - 无法显示图像

问题描述

我正在尝试使用 to_html 向 pandas 数据框添加一个向上和向下箭头,以获取电子邮件报告。

我正在使用 lambda 函数在数据框中的列值上输入一个向上和向下箭头,我知道图像 html 可以正常工作,因为我可以将它放在电子邮件的正文中并且它工作正常但是当我使用这个函数时以及它输出的熊猫格式化程序,如下图所示(ps。我知道 CID 与我的函数中的不同,我只是在测试一些东西)

有人知道为什么吗?或者有人有更好的方法吗?

熊猫格式化程序错误

称呼:

worst_20_accounts.to_html(index=False,formatters={'Last Run Rank Difference': lambda x: check_html_val_for_arrow(x)}))

功能:

def check_html_val_for_arrow(x):
    try:
        if x > 0:
            return str(x) + ' <img src="cid:image7">'
        elif x < 0:
            return str(x) + ' <img src="cid:image8">'
        else:
            return str(x)
    except:
        return str(x)

标签: htmlpandasdataframeemailformatter

解决方案


escape=False

默认情况下,该pandas.DataFrame.to_html方法会转义数据框值中的任何 html。

my_img_snippet = (
    "<img src='https://www.pnglot.com/pngfile/detail/"
    "208-2086079_right-green-arrow-right-green-png-arrow.png'>"
)
df =  pd.DataFrame([[my_img_snippet]])

然后

from IPython.display import HTML
HTML(df.to_html(escape=False))

在此处输入图像描述


style

您可以让styler对象处理渲染

df.style

在此处输入图像描述


推荐阅读