How to use `style` in conjunction with the `to_html` classes on a DataFrame?

Eric Hansen picture Eric Hansen · Mar 6, 2017 · Viewed 10.6k times · Source

I have a DataFrame like

df = pd.DataFrame(np.random.randn(10).reshape(2, 5))

df
#              0         1         2         3         4
#    0 -0.067162 -0.505401 -0.019208  1.123936  0.087682
#    1 -0.373212 -0.598412  0.185211  0.736143 -0.469111

I am trying to output this DataFrame as HTML, and was previously using to_html like

df.to_html(classes=['table', 'table-hover', 'table-bordered'], 
           float_format=lambda x: '{0:.3f}s'.format(x))

But then I came across the Style feature, and thought that it would be nice to have a styler for the floats in my DataFrame. Like

def colorize(num)
    color = 'red' if (np.isnan(num) or num > 0) else 'green'
    return 'color: %s' % color

which I can apply to my DataFrame with

df_styler = df.Style.applymap(colorize)

But now df_styler is a Styler object, and though it has a render method, I don't see how I can pass the classes list or float formatter which I was using with to_html anymore...

Is there a way that I can combine using Style functions and the CSS classes / formatters found in to_html?

Answer

Try this:

html = df.style.applymap(colorize) \
         .set_table_attributes('border="1" class="dataframe table table-hover table-bordered"') \
         .set_precision(3) \
         .render()

with open('d:/temp/a2.html', 'w') as f:
    f.write(html)

Result:

enter image description here