Tuesday, 18 October 2022

How to set a background color to cells in a multiindex table?

I have this multiindex column df:

None         INT        INT        INT        PP         PP         PP                       
DATE      2021-12-01 2021-12-02 2021-12-03 2021-12-04 2021-12-05 2021-12-06
0            1.0        0.0        2.0        2.0        4.0        2.0
1            NaN        NaN        NaN        NaN        NaN        NaN
2            0.0        0.0        2.0        0.0        3.0        4.0
3            0.0        2.0        2.0        2.0        3.0        2.0
4            0.0        0.0        0.0        0.0        0.0        0.0
5            0.0        0.0        0.0        0.0        0.0        0.0
6            0.0        0.0        0.0        0.0        0.0        0.0
7            2.0        1.0        0.0        1.0        2.0        0.0
8            NaN        NaN        NaN        NaN        NaN        NaN
9            0.0        0.0        0.0        0.0        0.0        0.0

I want to give a background color style to only values in 'PP' columns (and export to excel) based on their values (white to values = 0, lightgray to values = 1, etc.). So i have in mind this:

###############################################################################
n=len(df.columns)
def colors_excel(s):
    
    if s.PP == 0:
        return ['background-color: white']*n
    elif s.PP == 1:
        return ['background-color: lightgray']*n
    elif s.PP == 2:
        return ['background-color: gray']*n
    elif s.PP == 3:
        return ['background-color: yellow']*n
    elif s.PP == 4:
        return ['background-color: orange']*n
    elif s.PP == 5:
        return ['background-color: red']*n
    else:
        return ['background-color: black']*n 
###############################################################################
exceldata=df.style.apply(colors_excel, axis=0)

exceldata.to_excel('ROUTE/name_of_thefile.xlsx',
                     engine='openpyxl', index=True)

But this doesn't work in a multiindex column. And i don't want to drop the date of the multiindex columns. How can i sove this?

I will appreciate any help.

Thanks in advance.



from How to set a background color to cells in a multiindex table?

No comments:

Post a Comment