Apply style map when writing a DataFrame to html with pandas
<p>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.</p>

<pre><code>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 &lt; 0 else 'black'
    return 'color: %s' % color

s = df.style.applymap(color_negative_red)
s
</code></pre>

<p>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.</p>

<p>Here is how I'm writing the unformatted df:</p>

<pre><code>df.to_html(r'c:\temp\html.html')
</code></pre>

<p>*<a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/style.html</a></p>

<p>**<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html</a></p>

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

<pre><code>with open('html.html', 'w') as html:
    html.write(s.render())
</code></pre>

python pandas