简体   繁体   中英

How to make dataframe content in e-mail go red in html based off results using Python

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)

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>
    """
    

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM