python - 向 panda 数据框添加背景颜色

标签 python pandas pivot-table

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

我怎样才能实现这个目标?

最佳答案

您可以使用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)

关于python - 向 panda 数据框添加背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59968955/

相关文章:

python - Django Rest Framework 通过无法获取直通模型进行自引用多对多

python - 为什么定义顺序在 python2 中不可用?

python - 将字典列表转换为数据框

python - Pandas 风格背景渐变行和列

pandas - Pandas 更改数据透视表中列的顺序

python - 你如何用 Python 中的列表交叉检查字典?

python - 按索引列的条件过滤 pandas Dataframe 中的值

python - 带有类别的 pyplot 条形图

r - 使用VBA在excel中融化/ reshape ?

java - Apache POI : Excel Pivot Table - Row Label