Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to export a pandas dataframe styler object to html

I have formatted a pandas dataframe using .style, and would like to send out the formatted table as an email. However, styler objects are not compatible with the to_html function, instead I then tried to use the .render() function.

However, .render() seems to remove quite a lot of the formatting e.g. the table border disappears and some text becomes centred. I'm trying to avoid editing the html string produced by .render() but I understand that may not be possible.

What are my other options for sending out a formatted table as an email?

like image 254
dwdwd Avatar asked Apr 07 '17 14:04

dwdwd


People also ask

How do I export pandas DataFrame to HTML?

To render a Pandas DataFrame to HTML Table, use pandas. DataFrame. to_html() method. The total DataFrame is converted to <table> html element, while the column names are wrapped under <thead> table head html element.

What is a styler object Python?

Style property returns a styler object which provides many options for formatting and displaying dataframes. A styler object is basically a dataframe with some style. In this article, we will go through 10 examples to master how styling works.


2 Answers

I too was trying to format a dataframe something like the to_html function but with changes to font and color. Most of the Google found examples use the built in pandas styler functions for their examples, but I needed something simpler. The code that I ended up with was:

df = pd.DataFrame(np.random.randn(15).reshape(5,3))

print(df)
df_styled = df.style.format('{:,.2f}').set_properties(**{
    'font': 'Arial', 'color': 'red', 'text-align': 'center'})
df_styled.set_table_styles([{'props': [('background-color', 'MintCream'), ('color', 'blue'), ('font', 'Arial'), ('font-weight', 'bold')]}])
df_styled.set_table_attributes('border="1"')

with open('test.html', 'w') as f:
    f.write(df_styled.render())

Since I am relatively new to python and pandas I originally thought that the styler was added to the original dataframe. I now understand that the df.style..... returns a styled dataframe object which can handle further property and attribute changes before finally being rendered. In this sample I rendered the styled dataframe to a file which can then be opened with a browser to see the result. In my actual application I rendered the styled dataframe to a string object which was then sent in and email as a html mime type as the OP originally wanted.

like image 189
ChrisH Avatar answered Oct 15 '22 23:10

ChrisH


I had the same problem. so after rendering the Style object I created a text file and write the Style object into it. After exporting the text file, change the format to html and you should be fine.

f=open("styled_dataframe.txt","w")
f.write(df.render()) # df is the styled dataframe
f.close()
like image 32
osmancakirio Avatar answered Oct 15 '22 21:10

osmancakirio