I am trying to edit an excel file using pandas. What I would like to do is, for a chosen column and a specific threshold have all the cells in that column with values lower than the threshold to be colored 'green', above the threshold colored 'red' and if they are equal to the threshold then they will be 'yellow' (just to clarify, each column can have a different threshold). - I don't want to 3 color-scale (gradient format) like I've seen in other posts , i.e. all the green cells are the same green etc..
After several attempts my solution includes identical functions varying in just the "threshold" value, is there a way I could change it to just one function receiving the relevant threshold? or if anyone has a more elegant way to achieve the background coloring that would be extremely helpful.
Here is my code:
from openpyxl import Workbook
import pandas as pd
Threshold_1 = 31.5
Threshold_2 = 128
Threshold_3 = 250
df = pd.read_excel('Book1.xlsx', 'dashboard', engine='openpyxl')
def color_code_column_1(val):
if val > Threshold_1:
color = 'red'
elif val < Threshold_1:
color = 'green'
else:
color = 'yellow'
return 'background-color: {}'.format(color)
def color_code_column_2(val):
if val > Threshold_2:
color = 'red'
elif val < Threshold_2:
color = 'green'
else:
color = 'yellow'
return 'background-color: {}'.format(color)
def color_code_column_3(val):
if val > Threshold_3:
color = 'red'
elif val < Threshold_3:
color = 'green'
else:
color = 'yellow'
return 'background-color: {}'.format(color)
df = df.style \
.applymap(color_code_column_1, subset=['cars'])\
.applymap(color_code_column_2, subset=['shoes'])\
.applymap(color_code_column_3, subset=['shirts'])\
.applymap(color_code_column_3, subset=['pants'])\
.applymap(color_code_column_3, subset=['socks'])\
.applymap(color_code_column_3, subset=['ties'])\
.applymap(color_code_column_3, subset=['coats'])\
.applymap(color_code_column_3, subset=['glasses'])\
writer = pd.ExcelWriter('Book1.xlsx')
df.to_excel(writer, 'dashboard', index=False)
writer.save()
What I was trying to do is something like:
def color_code_column(val, Threshold):
if val > Threshold:
color = 'red'
elif val < Threshold:
color = 'green'
else:
color = 'yellow'
return 'background-color: {}'.format(color)
df = df.style \
.applymap(color_code_column(Threshold_1), subset=['cars'])\
- Note: By "color cells" I mean background color of the cells and not change the font color.
- Bonus! Where can I find which colors can be used (I was trying something like 'lightgreen' but it didn't work)