Pandas Conditional HTML output formatting - cell selection if value in range

I am creating an HTML report using the pd.to_html () method. Can anyone clarify how I can format cells with values ​​from -0.5 to 0.5 with a green back ground for specific columns of the data frame?

+4
source share
1 answer

You can format your own DataFrames using the attribute style(entered since pandas v0.17.1). An example of what you want:

df = pd.DataFrame(np.random.randn(5,5), columns=list('ABCDE'))

def highlight_vals(val, min=-0.5, max=0.5, color='green'):
    if min < val < max:
        return 'background-color: %s' % color
    else:
        return ''

df.style.applymap(highlight_vals, subset=['B', 'C', 'D'])

gives you

enter image description here

See this laptop for a complete example: http://nbviewer.jupyter.org/gist/jorisvandenbossche/8b74f71734cd6d75a58c5a048261a7a7

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

, :

with open('filename.html', 'w') as f:
    f.write(df.style.applymap(highlight_vals, subset=['B', 'C', 'D'])
                    .set_table_attributes("border=1").render())
+11

All Articles