1

How do I colour in cells below 1 as green and cells between 0 and 0.5 yellow for Column C.

Current output:

   A    B    C
0 TT    WW   -5
1 AA    WW   0
2 DD    WW   5

Desired:

enter image description here

The following code for me just writes to Excel with no colour change.

import pandas as pd
import numpy as np


df = pd.read_excel("C:\\13\\13\\13.xlsx")
def highlight_vals(val, min=-1111, max=1, color='green'):
    if min < val < max:
        return 'background-color: %s' % color
    else:
        return ''
df.style.applymap(highlight_vals, subset=['C'])

def highlight_vals(val, min=0, max=0.5, color='yellow'):
    if min < val < max:
        return 'background-color: %s' % color
    else:
        return ''
df.style.applymap(highlight_vals, subset=['C'])


writer = pd.ExcelWriter("C:\\13\\13\\zz.xlsx")
df.to_excel(writer, startrow=0, startcol=0, index = False)

writer.save()
0

1 Answer 1

1

This should work:

import pandas as pd
import numpy as np


df = pd.read_excel("C:\\13\\13\\13.xlsx")
def highlight_vals(val, min=-1111, max=1, color='green'):
    if min <= val <= max:
        return 'background-color: %s' % color
    else:
        return ''
style_1 = df.style.applymap(highlight_vals, subset=['C'])

def highlight_vals(val, min=0, max=0.5, color='yellow'):
    if min <= val <= max:
        return 'background-color: %s' % color
    else:
        return ''
style_2 = df.style.applymap(highlight_vals, subset=['C'])

style_1.use(style_2.export())

writer = pd.ExcelWriter("C:\\13\\13\\zz.xlsx")
style_1.to_excel(writer, startrow=0, startcol=0, index = False)

writer.save()

I kept both Styler objects, applied one on another and saved the resulting one to Excel instead of a dataframe. Also note that I fixed your conditions. Otherwise, you won't get yellow color because of min < val

Sign up to request clarification or add additional context in comments.

11 Comments

My Excel does not change using this
Positive.I am using windows 10. Copied that code exactly. Maybe its wrong approach. The output appears but no colour change
How do you run the code? If you run from Jupyter, you can check results after every time you apply new style like display(style_1). Each time you should see coloured tables
I am using pycharm. Perhaps there is colour change if I had Jupyter. Can this be written to excel though or in pandas you can only colour dataframes but change is not noticed in excel. Is xlsxwriter required?
Everything works fine for me from PyCharm as well. I don't know about xlsxwriter, but I had to install openpyxl
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.