Search code examples
pythonpandaspivot-table

Adding background color to panda dataframe


I have a pivot table created using Pandas looks like below: enter image description here

How can I achieve this?


Solution

  • You can create DataFrame of styles with Styler.apply and set rows by index value with loc:

    df = df.reset_index()
    
    def color(x):
        c1 = 'background-color: yellow'
        c2 = 'background-color: orange'
        c3 = 'background-color: green'
        c4 = 'background-color: blue'
        c = '' 
        #compare columns
        mask1 = x['Row Lbl'] == 'cashback'
        mask2 = x['Row Lbl'].isin(['GrandTot', 'with cashbak'])
        both = mask1 | mask2
        #DataFrame with same index and columns names as original filled empty strings
        df1 =  pd.DataFrame(c, index=x.index, columns=x.columns)
        #modify values of df1 column by boolean mask
        df1.loc[~both, 'price'] = c1
        df1.loc[~both, 'GrandTot'] = c2
        df1.loc[mask1, :] = c3
        df1.loc[mask2, :] = c4
        return df1
    
    df.style.apply(color, axis=None).to_excel('styled.xlsx', engine='openpyxl', index=False)