Search code examples
pythoncsspandasdataframeformatting

Conditional formatting Multiple Columns in Pandas Data Frame and saving as HTML for emailing


I have 2 fold issues:

  1. I need to conditionally format 2 different columns of a dataframe
  2. this dataframe should then be saved as html for email body with the formatting applied

below is a sample set of my dataframe:

df = pd.DataFrame([
   ['item 1', 96, 12],
   ['item 2', 90, 23],
   ['item 3', 92, 17]
], columns = list("ABC"))

I want to format the background of cells

in Col B as follows: Orange: if the cell value >=95 Blue: if the cell value is <=90

in Col C as follows: Green: if cell value <=15 Red: if cell value >20

No colors to be put if the condition is not satisfied (white background)

Once the dataframe is styled / formatted, I need to now save this dataframe with colors into HTML File which i will use in email body. How do i export the df to html with the formatting applied.

what would be the code for the same?

I do not know how to apply styles / whatever i have done so far, i am not able to see results in eclipse

below is some code i tried but fails:

import pandas as pd
def color_negative_red(value):
    if value >= 95:
        color = 'font-weight: bold; background-color: orange'
    elif value < 90:
        color = 'font-weight: bold; background-color: blue'
    return color

df = pd.DataFrame([
   ['item 1', 96, 12],
   ['item 2', 90, 23],
   ['item 3', 92, 17]
], columns = list("ABC"))

styled_df=df.style.apply(color_negative_red, subset=['B','C'])#.format({'B': "{:.2%}"})
df.to_html(r'd:\test.html')
print(styled_df.render())

Solution

  • I found a solution as follows:

    import pandas as pd
    df = pd.DataFrame([
       ['item 1', 96, 12],
       ['item 2', 90, 23],
       ['item 3', 92, 17]
    ], columns = list("ABC"))
    
    
    
    df_styled=df.style.apply(lambda x: ["background: orange" 
                                        if (colname=='B' and value >= 95 ) 
                                        else  "background: blue" 
                                        if (colname=='B' and value<=90) 
                                        else "background: green" 
                                        if (colname=='C' and value<=15)
                                        else "background: orange"
                                        if (colname=='C' and value>=20)
                                        else ""
                                        for colname,value in x.iteritems()], axis = 1)
    df_styled.to_html(r'd:\test_styled.html')