6

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?

3
  • What have you tried so far, have you got any samples of the code not working we can help you with? Commented Jun 5, 2016 at 5:18
  • Unfortunately even cant find any example to try Commented Jun 5, 2016 at 5:19
  • Have you had a look at this question? it might be some help. Commented Jun 5, 2016 at 5:20

1 Answer 1

18

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())
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, this is exactly what i looked. Will try
How can i add the path for HTML output? Want to print file in specific location. None of the examples doesn't show that. Thank you
@Felix you will have to write the string that render returns to a file yourself. I added an example how to do this.
Thank you, @joris. For some reason in saved html page coloring working fine but borders from table disappeared. Any thoughts on that?
You're correct. For some reason, the style template does not include border=1 in the table tag. You can add this with .set_table_attributes("border=1"). I updated the answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.