Python 向熊猫数据框添加背景色

Python 向熊猫数据框添加背景色,python,pandas,pivot-table,Python,Pandas,Pivot Table,我使用Pandas创建了一个透视表,如下所示: 如何实现这一点?您可以使用创建样式的数据框,并使用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 = ''

我使用Pandas创建了一个透视表,如下所示:


如何实现这一点?

您可以使用创建样式的数据框,并使用
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)

@yatu-不太容易,请重新打开。当然没有问题@jezMaybe这一个对你有用: