You can try doing this in two ways:
With set_table_styles
from 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
:
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 HTML
tweaking; so it may be more suited to your needs.
I hope this proves useful.