I am e-mailing a dataframe in the body of the e-mail. However, I want to format the dataframe results so that if my results are a specific value (non-0 value) then the text turns red.
Please see below for my function which I turn into a dataframe to be sent in an e-mail
def id_check():
df = pd.read_csv('filename.csv', low_memory=False)
missing_id = df["id"].isna().sum()
print("Number of records missing an id:", missing_id)
return missing_id
id_table = {
'Check' : ['ID Check'],
'Summary' : ['Number of records missing an ID'],
'Findings' : [id_check()]
}
df_id = pd.DataFrame.from_dict(id_table)
df_id.head()
the result looks like
Check Summary Findings
0 ID Check Number of records missing an ID 0
However, if the findings ever become != 0, I'd like the findings result to turn red. Is there a way to do that? Currently i am just outputting my results and by default it is black
See below for my html e-mail code.
msg = MIMEMultipart('mixed')
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = ','.join(TO)
html = f"""
<html><body>
<h1> </h1>
<p> Please see the the summary below {df_id.to_html(index=False)} </p>
</body></html>
"""
msg_text = MIMEText(html, 'html')
msg.attach(msg_text)
CodePudding user response:
Use lambda function with Styler.apply
for coloring red row if no 0
in Findings
column, Styler.hide
is for hide index, for html is used Styler.to_html
:
color= lambda x: (pd.DataFrame('', index=x.index, columns=x.columns)
.mask(x['Findings'].ne(0), 'color:red;'))
html = df_id.style.apply(color, axis=None).hide().to_html()
#for oldier pandas version use
#html = df_id.style.apply(color, axis=None).hide_index().render()
html = f"""
<html><body>
<h1> </h1>
<p> Please see the the summary below {html} </p>
</body></html>
"""