着色数据透视表熊猫数据框

时间:2020-02-03 14:05:22

标签: python pandas pandas.excelwriter

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

**Account** AA-PRD  AB-PRD  AC-PRD  AD-PRD

**Product** 10      20      30      50

PROD1       50      50      60      12

PROD2       44      78      567     678

PROD3       56      234     45      77

我要根据帐户名的开头为整个列应用颜色。例如:如果帐户名称以“ AA”开头的颜色为黄色,如果以“ AB”开头的则颜色为红色

我该如何在python中将其保存到excel文件中?在pd.pivot_table函数中,“帐户”已用作“列”。下面的代码用于创建数据透视表

df_summary_table = pd.pivot_table(df_final,values=["cost"],index = "Product", columns="Account")

1 个答案:

答案 0 :(得分:2)

您可以使用Styler.apply创建样式的DataFrame,并使用loc通过掩码设置行:

def color(x): 
   c1 = 'background-color: yellow'
   c2 = 'background-color: red'
   c = ''
   m1 = x.columns.str.startswith('AA')
   m2 = x.columns.str.startswith('AB')

   df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
   df1.loc[:, m1] = c1
   df1.loc[:, m2] = c2
   return df1

(df_summary_table.style.apply(color,axis=None)
                 .to_excel('styled.xlsx', engine='openpyxl', index=False))