使用.style选项或自定义CSS的pandas to_html?

tre*_*nch 15 python pandas

我正在关注熊猫的风格指南,它运作得很好.

如何通过Outlook使用to_html命令保留这些样式?文档似乎有点缺乏我.

(df.style
   .format(percent)
   .applymap(color_negative_red, subset=['col1', 'col2'])
   .set_properties(**{'font-size': '9pt', 'font-family': 'Calibri'})
   .bar(subset=['col4', 'col5'], color='lightblue'))

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.Subject = subject_name
mail.HTMLbody = ('<html><body><p><body style="font-size:11pt; 
font-family:Calibri">Hello,</p> + '<p>Title of Data</p>' + df.to_html(
            index=False, classes=????????) '</body></html>')
mail.send
Run Code Online (Sandbox Code Playgroud)

to_html文档显示我可以在to_html方法中放入一个类命令,但我无法弄明白.看起来我的数据帧似乎没有我指定的风格.

如果我尝试:

 df = (df.style
       .format(percent)
       .applymap(color_negative_red, subset=['col1', 'col2'])
       .set_properties(**{'font-size': '9pt', 'font-family': 'Calibri'})
       .bar(subset=['col4', 'col5'], color='lightblue'))
Run Code Online (Sandbox Code Playgroud)

然后df现在是一个Style对象,你不能使用to_html.

编辑 - 这是我目前正在修改我的表格.这有效,但我无法保留熊猫提供的.style方法的很酷的功能.

email_paragraph = """
<body style= "font-size:11pt; font-family:Calibri; text-align:left; margin: 0px auto" >
"""

email_caption = """
<body style= "font-size:10pt; font-family:Century Gothic; text-align:center; margin: 0px auto" >
"""


email_style = '''<style type="text/css" media="screen" style="width:100%">
    table, th, td {border: 0px solid black;  background-color: #eee; padding: 10px;}
    th {background-color: #C6E2FF; color:black; font-family: Tahoma;font-size : 13; text-align: center;}
    td {background-color: #fff; padding: 10px; font-family: Calibri; font-size : 12; text-align: center;}
  </style>'''
Run Code Online (Sandbox Code Playgroud)

den*_*ien 31

添加style到链式分配后,您将对某个Styler对象进行操作.该对象有一个render方法来将html作为字符串.所以在你的例子中,你可以这样做:

html = (
    df.style
    .format(percent)
    .applymap(color_negative_red, subset=['col1', 'col2'])
    .set_properties(**{'font-size': '9pt', 'font-family': 'Calibri'})
    .bar(subset=['col4', 'col5'], color='lightblue')
    .render()
)
Run Code Online (Sandbox Code Playgroud)

然后html在您的电子邮件中包含而不是df.to_html().

  • 实际上,我只是注意到条形图没有显示在 Outlook 电子邮件中。不过其他一切都运行良好。任何想法如何让它显示? (2认同)