Skip to content Skip to sidebar Skip to footer

Using Df.style.applymap To Color Cell's Background For Multiple Sheet Excel

MRE created with help from https://jakevdp.github.io/PythonDataScienceHandbook/03.05-hierarchical-indexing.html, amazing summary on Hierarchical indexing MRE: index = pd.MultiIndex

Solution 1:

It seems you need chain both rows, because df.style.applymap(coloring) is not assigned back:

df.style.applymap(coloring).to_excel(writer, sheet_name=g)

instead:

df.style.applymap(coloring)
df.to_excel(writer, sheet_name=g)

Or assign back:

df = df.style.applymap(coloring)
df.to_excel(writer, sheet_name=g)

EDIT:

for me working well, if values in list are integers, because if use np.array for mixed data - strings with numbers numpy convert all data to objects:

index = pd.MultiIndex.from_product([[2013, 2014,2015, 2016]],
                                   names=['year'])
columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'group']])

data = np.array([[1,2,3,4,5,"g1"],
                 [3,6,1,3,2,"g2"],
                 [3,6,1,2,3,"g1"],
                 [6,7,8,11,23,"g2"]])

all_df = pd.DataFrame(data, index=index, columns=columns)

print (all_df.dtypes)

Bob    HR       object
       group    object
Guido  HR       object
       group    object
Sue    HR       object
       group    object
dtype: object

So if pass nested lists to DataFrame all working well for me:

index = pd.MultiIndex.from_product([[2013, 2014,2015, 2016]],
                                   names=['year'])
columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'group']])

data = [[1,2,3,4,5,"g1"],
        [3,6,1,3,2,"g2"],
        [3,6,1,2,3,"g1"],
        [6,7,8,11,23,"g2"]]

all_df = pd.DataFrame(data, index=index, columns=columns)

print (all_df.dtypes)
Bob    HR        int64
       group     int64
Guido  HR        int64
       group     int64
Sue    HR        int64
       group    object
dtype: object

def coloring(val):
    color = '#EDFFE7' if val in lst else 'white'
    return f"background-color: {color}"

writer = pd.ExcelWriter("test.xlsx", engine="xlsxwriter")

groups = ["g1", "g2"]
lst = [1,2,3]


for g in groups:
    df = all_df.loc[all_df[("Sue","group")] == g].copy()
    #print (df)
    df.style.applymap(coloring).to_excel(writer, sheet_name=g)

writer.save()

Post a Comment for "Using Df.style.applymap To Color Cell's Background For Multiple Sheet Excel"