I want to visualise some data, so I need to colour my dataframe in gradient colour depending on the value and I want to export that in Excel.
What I have now, is that it exports the grey colour part, but does not export the gradient yellow part. Could you help edit my code, or maybe you have another way of doing that task?
My current code:
def highlight_negative(val):
if val > 1:
if val <500:
color = 'dimgrey'
elif val >=500 and val < 1000:
color = 'lightgray'
else:
color = 'None'
else:
color = None
return f'background-color: {color}'
def gradient_color(val):
# Gradient colour yellow (low value) to white (high value)
if val >=0 and val <=1:
min_val = 0
max_val = 1
range_val = max_val - min_val
if range_val == 0:
# if all the values are equal - return white colour
return 'background-color: rgb(255,255,255)'
else:
# Setting RGB component to gradient from yellow to white
r = 255
g = 255
b = int(255 * (max_val - val) / range_val)
else:
r = None
g = None
b = None
return f'background-color: rgb({r},{g},{b})'
# Apply gradient and highlight design to DataFrame
styled_df = df.style.applymap(gradient_color, subset=df.columns[2:]).applymap(highlight_negative, subset=df.columns[2:]).format(precision=2)
styled_df.to_excel('styled_df.xlsx', engine='openpyxl')
Using Conditional Formatting does not restrict the automation.
Rather than colouring the cells in Pandas and writing to Excel you are just colouring the cells in Excel instead, using Openpyxl to apply Conditional Formatting.
It shouldn't be any different unless you have a need to access the DataFrame with styling included for some reason.
Conditional Formatting does have the advantage that if you need to change any values manually in Excel for whatever reason, the fill colour will update automatically.
Anyway you can make your choice what works better for your scenario.
As @Vikas notes it would be better if you provided your dataframe and expected result so I'm guessing what your data might look like based on your code.
It seems the DF has numeric values and you want to background colour based on;
In this example I have a DataFrame with various values to cover the 4 ranges above. After writing the DF to excel we use Openpyxl to apply the Conditional Formatting.
The data in Excel will look like this

CF is applied to cells in the range B2:E5. As noted if you change a value the bg colour will update to suit.