【问题标题】:Adding background color to panda dataframe为熊猫数据框添加背景颜色
【发布时间】:2020-05-15 01:27:58
【问题描述】:

我有一个使用 Pandas 创建的数据透视表,如下所示:

我怎样才能做到这一点?

【问题讨论】:

标签: python pandas pivot-table


【解决方案1】:

您可以使用Styler.apply 创建样式的DataFrame,并使用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)

【讨论】:

    猜你喜欢
    • 2014-06-01
    • 2021-07-03
    • 2015-03-29
    • 2020-01-08
    • 2016-07-26
    • 2016-12-09
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    相关资源
    最近更新 更多