Pandas DataFrame to HTML: Formatting the values to display centered
Asked Answered
I

5

8

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?

Idaho answered 18/4, 2018 at 15:39 Comment(0)
A
11

I would suggest using the formatters within the to_html function, description of the parameter:

formatters : list or dict of one-parameter functions, optional formatter functions to apply to columns’ elements by position or name, default None. The result of each function must be a unicode string. List must be of length equal to the number of columns.

Example if you want to make all your Name column bold:

df.to_html(formatters={'Name': lambda x: '<b>' + x + '</b>'})

Let me know whether it works!

Aeromancy answered 18/4, 2018 at 15:47 Comment(10)
This makes sense to me. Can you include an example where you use formatters to center all cell values (all columns)?Idaho
@RichardGolz If it's only for the purpose of centering the cells, I would probably just modify the string you get after using df.to_html by adding align='center' within the <table> tag so it becomes <table align='center'>, that to me is more straight forward than centering each column.Aeromancy
something like html[:6] + ' align="center"' + html[6:]Aeromancy
I now have <table align="center" border="1" class="dataframe"> but it still appears to be left-aligned. Sigh. Below that I do see <thead> <tr style="text-align: right;"> - wonder if that has anything to do with it (although my data is appearing left aligned)Idaho
Does html.replace('text-align: right;', 'text-align: center') solve the issue?Aeromancy
No, in fact it won't even replace the <tr style="text-align: right;"> for whatever reason. HmmIdaho
Let us continue this discussion in chat.Idaho
I'm accepting your answer as correct due to the "modifying the string you get after using df.to_html"Idaho
I Came here while searching for formatting a multi-level column. formatters={'Name': lambda x: '<b>' + x + '</b>'}. Here it is referring to the main column x. How can i refer to a sub-column within the same column for formatting.Ember
You forget to add escape=False, otherwise the HTML tag will get escaped. (< becomes &lt;)Elderberry
I
8

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)
Idaho answered 18/4, 2018 at 16:40 Comment(1)
Or like this with CSS for example for both TD and TH tags html = str(df_group[:5].to_html()).replace('<td>', '<td style="text-align: left">').replace('<th>', '<th style="text-align: left">')Sanson
C
5

I solved this problem with make a little change in CSS and python code. Here's my python code :

dft.to_html(classes=["table-bordered", "table-striped", "table-hover", "isi"]

I make "isi" class and write it in CSS like this :

.isi {
text-align:center; }

Here's the result Values Centered

Collogue answered 11/9, 2020 at 5:6 Comment(1)
For those not familiar with CSS, the code should be complete. The code sample gives 'invalid syntax' error on the definition of "isi"Doolie
A
1

if you want the entire table to be centred just use the justify parameter:

 df.to_html(justify="center")
Acaulescent answered 29/3, 2023 at 17:13 Comment(2)
The justify= parameter justifies column labels (see docs).Schwejda
This solution worked for me with **justify="left"**. Simple and Easy. Thanks.Acrefoot
M
0

I suggest to use the Styler object instead of the to_html() parameters. This way you can separate the styling from the rendering.

# create test dataframe
df = pd.DataFrame({"what": ["a", "b", "c", "d"], "howmuch": [55, 60, 101, 78]})

# create a Styler
df_styled = df.style.set_properties(
    **{"text-align": "center", "font-weight": "bold"}
).hide(axis="index")

# export html with style
df_styled.to_html("myFile.html")
Migraine answered 5/10, 2022 at 14:22 Comment(2)
how can you align the entire dataframe table container on an html page?Prince
@Prince check out the pandas.io.formats.style.Styler class. There is certianly a way to add custom CSS.Migraine

© 2022 - 2025 — McMap. All rights reserved.