Python3 如何在电子邮件中发送 Pandas Dataframe

use*_*102 6 dataframe pandas

def call_panda():
    filename = 'C:\\file.csv'
    cols_to_use = ['col1', 'col2', 'col3', 'col4']
    df = pd.read_csv(filename, nrows= 5,usecols=cols_to_use,index_col='col1')               
    # Send email
    me = 'me@email.com'
    you = 'you@email.com'
    textfile = df
    with open(textfile, 'rb') as fp:
        msg = MIMEText(fp.read())
        msg['Subject'] = 'Contents of file'
        msg['From'] = me
        msg['To'] = you
        s = smtplib.SMTP('mailhost.acme.net')
        s.sendmail(me, [you], msg.as_string())
        s.quit()
Run Code Online (Sandbox Code Playgroud)

错误消息是 open(textfile, 'rb') as fp: TypeError: Expected str, bytes or os.PathLike object, not DataFrame

Eva*_*van 5

熊猫有一个df.to_html特点。

https://pandas.pydata.org/pandas-docs/stable/ generated/pandas.DataFrame.to_html.html

复制克里斯·阿尔本:https://chrisalbon.com/python/data_wrangling/pandas_join_merge_dataframe/

import pandas as pd

raw_data = {
        'subject_id': ['1', '2', '3', '4', '5'],
        'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'], 
        'last_name': ['Anderson', 'Ackerman', 'Ali', 'Aoni', 'Atiches']}
df_a = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name', 'last_name'])
df_a.to_html('df.html')
Run Code Online (Sandbox Code Playgroud)

从这里,查看此线程以获取电子邮件提示:使用 Python 发送 HTML 电子邮件

您似乎需要附加 HTML 文件;我不确定它是否会在线显示,而且我没有可以检查的邮件服务器。


Cho*_*Cho 0

在上面的代码中,df定义为textfile当前内存中存在的数据。因此,该with open命令无法执行。with open是将硬盘上存储的任何文件加载到内存中的函数。