[英]Coloring pivot table pandas dataframe
I have a pivot table created using pandas which looks like below:我有一个使用熊猫创建的数据透视表,如下所示:
**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
I want to apply color for the entire column based on account name starts with.我想根据帐户名称开头为整个列应用颜色。 Ex: If account name starts with "AA" color=yellow, if starts with "AB" then color = red例如:如果帐户名称以“AA”开头,颜色=黄色,如果以“AB”开头,则颜色=红色
How can I do that in python and save it into excel file?我怎样才能在python中做到这一点并将其保存到excel文件中? "Account" has been used as "columns" in pd.pivot_table function. “帐户”已用作 pd.pivot_table 函数中的“列”。 Used below code to create the pivot table使用下面的代码来创建数据透视表
df_summary_table = pd.pivot_table(df_final,values=["cost"],index = "Product", columns="Account")
You can create DataFrame of styles with Styler.apply
and set rows by masks with loc
:您可以使用 Styler.apply 创建样式的Styler.apply
并使用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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.