I am pretty new to Python and to the Jupyter Notebook. So any help will be appreciated. I was able to color specific cells of my DataFrame following this question.
Now suppose that I have that table with the "style" on it (as the one in the accepted answer) and I wish to send it by e-mail to someone (in this case, myself) without losing any of the format (it should contain the colored cells, the border, and everything else).
I have tried using the .render() function and then attaching the HTML code to the body of the e-mail but I keep getting a borderless table with no structure. I have followed this post to code the e-mail part. The only difference is that I am not using the "plain text" part.
Also, how can I add more features to the table itself? Like adding table title, modify the spacing between the columns, increasing or decreasing the font size?
Thank you!
Here is a function that I use for this very case. The for loop is to create banded rows.
def html_style_basic(df,index=True):
import pandas as pd
x = df.to_html(index = index)
x = x.replace('<table border="1" class="dataframe">','<table style="border-collapse: collapse; border-spacing: 0; width: 25%;">')
x = x.replace('<th>','<th style="text-align: left; padding: 2px; border-left: 1px solid #cdd0d4;" align="left">')
x = x.replace('<td>','<td style="text-align: left; padding: 2px; border-left: 1px solid #cdd0d4; border-right: 1px solid #cdd0d4;" align="left">')
x = x.replace('<tr style="text-align: right;">','<tr>')
x = x.split()
count = 2
index = 0
for i in x:
if '<tr>' in i:
count+=1
if count%2==0:
x[index] = x[index].replace('<tr>','<tr style="background-color: #f2f2f2;" bgcolor="#f2f2f2">')
index += 1
return ' '.join(x)
Based on the fact that you already got a styled DataFrame through Format the color of a cell in a pandas dataframe according to multiple conditions , then you can save it to a html file.
with open('DataFrame.html', 'a') as f:
f.write(df.render() )
For the further need of customization, visit https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html .
I was able to find an answer to my question following this post: how to draw a beautiful colorful table with pandas or other package in Python?
Essentially, if you use the .set_table_styles to add the borders after adding the colors to the cells, the html code sent by e-mail will be displayed properly. I hope it helps anyone with the same issue.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.