Home > Software engineering >  Change colour of text of a column based on the value of another column within the same dataframe usi
Change colour of text of a column based on the value of another column within the same dataframe usi

Time:07-01

I am trying to change the color of text in a column dependent on the value of another column within a data frame and then host on Streamlit app.

The dataframe contains 5 columns. The column names are as follows:-

df.columns = ['energy_kwh', 'energy_cumsum_kwh', 'threshold', 'energy_consumption', 'Check']

I want the 'check' column to show that within a given row, if the 'threshold' column is greater than the 'energy_consumption' columns then the text in the 'check' column of the given row should be green but if the 'energy_consumption column' is greater than the 'threshold' column within a given row then the text should be red. I have attempted to use the df.style.apply and df.style.applymap method but have been unable to find a solution. Please see below my attempts:-

  1. def highlight(val):
        color = 'red' if val.energy_consumption > val.threshold else 'green'
        return 'color: %s' % color
    
    df_style = df.style.applymap(highlight, subset=['Check'])
    st.dataframe(df_style)
    
  2. def highlight(row):
        if row['energy_consumption'] > row['threshold']:
            return 'color: %s' % 'red'
        elif row['energy_consumption'] < row['threshold']:
            return 'color: %s' % 'green'
    
    df_style = df.style.applymap(highlight, subset=['Check'])
    
    st.dataframe(df_style)
    
  3. col = df['threshold']
    
    def color_survived(col):
        color = 'red' if df['threshold'] <(df.energy_consumption) 
                      else df['threshold'] <(df.energy_consumption) else 'green'
        return 'color: %s' % color
    
    st.table(df.style.applymap(color_survived), subset=['energy_kwh'])
    

I would like the final dataframe to look like this:-

Final table visualisation

Would appreciate help on how to approach this problem and also what I am doing wrong.

CodePudding user response:

applymap evaluates each cell individually but you need to apply the highlighter on the entire table, which can be achieved via apply.

def highlighter(x):
    # initialize default colors
    color_codes = pd.DataFrame('', index=x.index, columns=x.columns)
    # set Check color to red if consumption exceeds threshold green otherwise
    color_codes['Check'] = np.where(x['energy_consumption'] > x['threshold'], 'color:red', 'color:green')
    return color_codes

# apply highlighter to df
df_style = df.style.apply(highlighter, axis=None)
  • Related