简体   繁体   English

Pandas 数据帧在 email 中发送时无法正确显示/格式化?

[英]Pandas data frame is not displaying/formatting correctly when being sent in an email?

When I print the dataframe in python, it is well formatted and centre aligned.当我在 python 中打印 dataframe 时,它的格式很好并且居中对齐。 However, when I send the dataframe in an email, the data and column headers are all over the place.但是,当我在 email 中发送 dataframe 时,数据和列标题到处都是。

df1 = pd.DataFrame(data=data1, columns=cols1)
print(df1)

Output Output

      Race               Horse   Odds         W%
0  Ascot R1   Cliffs Of Comfort    2.5  40.000000
1  Ascot R1          Tommy Blue    2.8  35.714286
2  Ascot R1             Semigel   12.2   8.196721
3  Ascot R1          River Beau   13.0   7.692308
4  Ascot R1          Rocky Path   21.0   4.761905
5  Ascot R1     Melody's Secret   41.0   2.439024
6  Ascot R1         Art Admirer  201.0   0.497512
7  Ascot R1  Lies 'N' Deception  151.0   0.662252
8  Ascot R1        Express Time   11.0   9.090909
9  Ascot R1       Single Finger  201.0   0.497512

Code for sending email发送代码 email

for data in df1, df2:
  datetime = datetime.now()
  subject = f'Market Efficiency Update - {datetime}'
  body = f'Hi Harrison,\n\nMarket efficiency is:{df2} \n\n{df1}'
  message = f'Subject: {subject}\n\n{body}'
  mail = smtplib.SMTP('smtp.gmail.com', 587)

I think pandas function DataFrame.to_string() would help you here:我认为pandas function DataFrame.to_string()会帮助你:

for data in df1, df2:
    (...)
    df1_str = df1.to_string()
    body = f'Hi Harrison,\n\nMarket efficiency is:{df2} \n\n{df1_str}'
    (...)

Try converting DataFrame to HTML format as below:尝试将 DataFrame 转换为 HTML 格式如下:

  for data in df1, df2:
      datetime = datetime.now()
      subject = f'Market Efficiency Update - {datetime}'
      body = f'Hi Harrison,\n\nMarket efficiency is:{df2.to_html()} \n\n{df1.to_html()}'
      message = f'Subject: {subject}\n\n{body}'
      mail = smtplib.SMTP('smtp.gmail.com', 587)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM