Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas HTML Output Conditional Formatting - Highlight cell if value in range

I am building report in HTML format using pd.to_html() method. Can anyone clarify how can i format cells with values between -0.5 and 0.5 with green back ground for particular columns of data frame?

like image 904
Felix Avatar asked Jun 05 '16 04:06

Felix


1 Answers

You can do custom formatting of DataFrames using the style attribute (introduced starting from pandas v0.17.1). An example to do 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 notebook for the full example: http://nbviewer.jupyter.org/gist/jorisvandenbossche/8b74f71734cd6d75a58c5a048261a7a7

And see the docs for more example how to format the dataframe: http://pandas.pydata.org/pandas-docs/stable/style.html

To write the output to a file, you can do:

with open('filename.html', 'w') as f:
    f.write(df.style.applymap(highlight_vals, subset=['B', 'C', 'D'])
                    .set_table_attributes("border=1").render())
like image 185
joris Avatar answered Nov 12 '22 15:11

joris