Reputation: 401
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
?
Upvotes: 8
Views: 38244
Reputation: 11
if you want the entire table to be centred just use the justify parameter:
df.to_html(justify="center")
Upvotes: 1
Reputation: 434
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")
Upvotes: 0
Reputation: 51
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
Upvotes: 5
Reputation: 401
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)
Upvotes: 8
Reputation: 3358
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!
Upvotes: 12