Pandas dataframe.to_html() - 为标题添加背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41445684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:42:23  来源:igfitidea点击:

Pandas dataframe.to_html() - add background color to header

pythonpandas

提问by Zedak

I am trying to send multiple dataframes as tables in an email. Using df.to_html()I am able to render a HTML string for the table which I am attaching as the part of the email body. I am successfully able to get the tables in the email.

我正在尝试在电子邮件中将多个数据帧作为表格发送。使用df.to_html()我能够为我作为电子邮件正文的一部分附加的表格呈现 HTML 字符串。我成功地获得了电子邮件中的表格。

html.append(table.to_html(na_rep = " ",index = False))
body = '\r\n\n<br>'.join('%s'%item for item in html)
msg.attach(MIMEText(body, 'html'))

But how do I add background color to the header of these tables?

但是如何将背景颜色添加到这些表格的标题中?

回答by Abdou

You can try doing this in two ways:

您可以尝试通过两种方式执行此操作:

With set_table_stylesfrom pandas.DataFrame.style:

随着set_table_styles来自pandas.DataFrame.style

import pandas as pd
import numpy as np

# Set up a DataFrame
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
df.iloc[0, 2] = np.nan


df_html_output = df.style.set_table_styles(
    [{'selector': 'thead th',
    'props': [('background-color', 'red')]},
    {'selector': 'thead th:first-child',
    'props': [('display','none')]},
    {'selector': 'tbody th:first-child',
    'props': [('display','none')]}]
).render()

html.append(df_html_output)
body = '\r\n\n<br>'.join('%s'%item for item in html)
msg.attach(MIMEText(body, 'html'))

Or with .to_html:

或与.to_html

df_html_output = df.to_html(na_rep = "", index = False).replace('<th>','<th style = "background-color: red">')

html.append(df_html_output)
body = '\r\n\n<br>'.join('%s'%item for item in html)
msg.attach(MIMEText(body, 'html'))

The second one provides the option of removing the index column during the export (to_html) without having to do too much HTMLtweaking; so it may be more suited to your needs.

第二个提供了在导出 ( to_html)期间删除索引列的选项,而无需进行太多HTML调整;所以它可能更适合您的需求。

I hope this proves useful.

我希望这证明是有用的。

回答by Oxymoron88

I would recommend using Jinja2 for convenient HTML formatting. Just create a word document, add two lines {{Header}} with whatever background colour you would like, {{DF}}, add a page break and save this as html. Now use Jinja2 to render the templates. Below is a sample code of how Jinja2 can be used:

我建议使用 Jinja2 来方便的 HTML 格式。只需创建一个 word 文档,添加两行 {{Header}} 和您想要的任何背景颜色,{{DF}},添加一个分页符并将其保存为 html。现在使用 Jinja2 来渲染模板。下面是如何使用 Jinja2 的示例代码:

from jinja2 import Environment, FileSystemLoader
import StringIO
import pandas as pd

Template_Path = '/home/test/'
DF = [pd.DataFrame()]*5 # List of Dataframes
Header_Text = ['header']*5 # list of headers
env = Environment(loader=FileSystemLoader(Template_Path))
template = env.get_template('PDF_Temp.html') # name of your html template

Master_HTML = ''
for x in range(len(DF)):
    buf = StringIO.StringIO()
    DF_HTML = DF[x].to_html(buf)
    template_vars = {"Header"         : Header_Text[x]  ,
                     "DF"             : buf.getvalue()
                    }

    # Create PDF
    Master_HTML += template.render(template_vars) 

FN = 'test.html'
with open(FN, "w") as f:
    f.write(Master_HTML.encode('utf-8') )

This is a nice tutorial on Jinja2: http://pbpython.com/pdf-reports.html

这是一个关于 Jinja2 的不错的教程:http: //pbpython.com/pdf-reports.html