Python 将熊猫数据帧数据作为 html 电子邮件发送

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19679820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:21:20  来源:igfitidea点击:

Send pandas dataframe data as html e-mail

pythonhtmlemailpandas

提问by Nilani Algiriyage

I want to send a pandas dataframe data as an HTML e-mail. Based on thispost I could create an html with the dataframe. Code

我想将 Pandas 数据帧数据作为 HTML 电子邮件发送。基于这篇文章,我可以用数据框创建一个 html。代码

import pandas as pd
import numpy as np

HEADER = '''
<html>
    <head>

    </head>
    <body>
'''
FOOTER = '''
    </body>
</html>
'''

df = pd.DataFrame([[1.1, 1.1, 1.1, 2.6, 2.5, 3.4,2.6,2.6,3.4,3.4,2.6,1.1,1.1,3.3], list('AAABBBBABCBDDD')]).T
with open('test.html', 'w') as f:
    f.write(HEADER)
    f.write(df.to_html(classes='df'))
    f.write(FOOTER)

Now I want to send this as a html e-mail. I tried this. Can not figure out how to attach the html file?

现在我想将此作为 html 电子邮件发送。我试过这个。无法弄清楚如何附加 html 文件?

采纳答案by Nilani Algiriyage

Finally found. This is the way it should be done.

终于找到了。这是它应该做的方式。

filename = "test.html"
f = file(filename)
attachment = MIMEText(f.read(),'html')
msg.attach(attachment)

回答by Johnny V

Pandas has a function for this.

大熊猫有一个函数

This will give the the html code for the table, after which you can embed it into an email with:

这将为表格提供 html 代码,之后您可以将其嵌入到电子邮件中:

df = DataFrame(data)

email = " some html {df} lah lah"

email = email.format(df=df.to_html())