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

Zed*_*dak 14 python pandas

我正在尝试将多个数据帧作为电子邮件中的表格发送.使用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'))
Run Code Online (Sandbox Code Playgroud)

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

Abd*_*dou 19

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

随着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'))
Run Code Online (Sandbox Code Playgroud)

或者.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'))
Run Code Online (Sandbox Code Playgroud)

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

我希望这证明是有用的.