sparrow
sparrow

Reputation: 11460

Apply style map when writing a DataFrame to html with pandas

I want to output a pandas DataFrame to .html and also apply a style. The documentation* gives this example which displays negative values as red.

import pandas as pd
import numpy as np

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

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

s = df.style.applymap(color_negative_red)
s

Can I output the formatted df using the "to_html" method? From that documentation** I see that there is a "formatters" option but I can't figure out how to apply it in this case.

Here is how I'm writing the unformatted df:

df.to_html(r'c:\temp\html.html')

*http://pandas.pydata.org/pandas-docs/stable/style.html

**http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html

Upvotes: 3

Views: 3328

Answers (1)

Romain
Romain

Reputation: 21878

I don't know if it is the best (or idiomatic) way to do that, but it should work:

with open('html.html', 'w') as html:
    html.write(s.render())

Upvotes: 4

Related Questions