Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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.

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?

like image 858
Zedak Avatar asked Jan 03 '17 14:01

Zedak


2 Answers

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.

like image 178
Abdou Avatar answered Oct 09 '22 00:10

Abdou


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:

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

like image 33
Oxymoron88 Avatar answered Oct 09 '22 02:10

Oxymoron88