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

问题描述 投票:12回答:2

我跟随the style guide for 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

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'))

然后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>'''
python pandas
2个回答
23
投票

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()
)

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


1
投票

这不是一个奢侈/ pythonic解决方案。我在to_html()方法生成的html代码之前插入了直接css文件的链接,然后我将整个字符串保存为html文件。这对我很有用。

dphtml = r'<link rel="stylesheet" type="text/css" media="screen" href="css-table.css" />' + '\n'
dphtml += dp.to_html()

with open('datatable.html','w') as f:
    f.write(dphtml)
    f.close()
    pass
© www.soinside.com 2019 - 2024. All rights reserved.