Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas DataFrame to HTML: Formatting the values to display centered

I have a pandas DataFrame and am using the DataFrame.to_html method to generate a table I can send within an HTML email message. I simply want the values in certain columns to be centered, but would also like to know in general how to apply formatting to the table. I have tried applying the documentation found HERE as well as using df.style before using to_html like so:

df.style.set_properties(**{'text-align':'center'})

But i am still getting all of my values left-aligned (other than the headers, which are centered).

What is the correct way to center all (or a subset) of my column values, and what are the other options available for formatting? (e.g. bolding text, changing background or border colors, etc.)

Further, at what stage should this formatting be applied? Within the to_html method or prior to it as I tried with df.style? Thanks!

like image 462
Richard Golz Avatar asked Dec 06 '22 12:12

Richard Golz


1 Answers

After some research and the help of Bubble Bubble Bubble Gut, this can be easily done by replacing all of the <tr> tags with <tr align="center"> via:

html2 = html.replace('<tr>', '<tr align="center">')
print(html2)
like image 96
Richard Golz Avatar answered Jun 01 '23 23:06

Richard Golz