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

pandas to_html using the .style options or custom CSS?

我一直在关注 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。

编辑 - 这是我目前正在做的修改表格的工作。这行得通,但我无法保留 pandas 提供的 .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>'''

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

这不是奢侈/pythonic 解决方案。我在 to_html () 方法生成的 html 代码之前将 link 直接插入 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)

选择 table(jupyter 中呈现的、样式化的数据框小部件)和 copy-pasting 到电子邮件正文对我有用(使用 outlook office)。

无需手动 html 提取、保存、加载或类似操作。