【问题标题】:Apply shading, formatting and borders to pivoted dataframe将阴影、格式和边框应用于旋转数据框
【发布时间】:2021-12-09 07:19:42
【问题描述】:

我有以下数据已被透视:

pip install Jinja2

import pandas as pd
import numpy as np
from numpy import rec, nan

a=rec.array([('FY20',  361.410592  ,  nan, 21.97, nan, 'Total', 'Fast'),
       ('FY21',  359.26952604,  -1., 22.99,  5., 'Total', 'Fast'),
       ('FY22',  362.4560529 ,   1., 22.77, -1., 'Total', 'Fast'),
       ('FY23',  371.53543252,   2., 21.92, -4., 'Total', 'Fast'),
       ('FY24',  374.48894494,   1., 21.88, -0., 'Total', 'Fast'),
       ('FY25',  377.09481613,   1., 21.85, -0., 'Total', 'Fast'),
       ('FY20',   67.043756  ,  nan, 21.  , nan, 'Homes', 'Fast'),
       ('FY21',  110.12145222,  63., 20.95, -0., 'Homes', 'Fast'),
       ('FY22',  117.46526727,   7., 20.73, -1., 'Homes', 'Fast'),
       ('FY23',  125.83482531,   7., 18.99, -8., 'Homes', 'Fast'),
       ('FY24',  126.16748411,   1., 18.95, -0., 'Homes', 'Fast'),
       ('FY25',  127.786528  ,   1., 18.96,  0., 'Homes', 'Fast'),
       ('FY20',  294.366836  ,  nan, 22.19, nan, 'Businesses', 'Fast'),
       ('FY21',  249.14807381, -15., 23.89,  8., 'Businesses', 'Fast'),
       ('FY22',  245.99078563,  -2., 23.74, -1., 'Businesses', 'Fast'),
       ('FY23',  245.70060721,   0., 23.42, -1., 'Businesses', 'Fast'),
       ('FY24',  247.32146083,   1., 23.37, -0., 'Businesses', 'Fast'),
       ('FY25',  250.30828813,   1., 23.33, -0., 'Businesses', 'Fast'),
       ('FY20',  184.631684  ,  nan, 15.47, nan, 'Total', 'Medium'),
       ('FY21',  274.25718084,  49., 15.53,  0., 'Total', 'Medium'),
       ('FY22',  333.23835913,  21., 15.33, -1., 'Total', 'Medium'),
       ('FY23',  357.33167549,   7., 15.52,  1., 'Total', 'Medium'),
       ('FY24',  367.84796426,   3., 15.53,  0., 'Total', 'Medium'),
       ('FY25',  370.1664439 ,   1., 15.53,  0., 'Total', 'Medium'),
       ('FY20',   46.522416  ,  nan, 17.89, nan, 'Homes', 'Medium'),
       ('FY21',   97.63428522, 112., 18.72,  5., 'Homes', 'Medium'),
       ('FY22',  141.25547499,  46., 17.86, -5., 'Homes', 'Medium'),
       ('FY23',  157.06766598,  11., 18.33,  3., 'Homes', 'Medium'),
       ('FY24',  163.02337094,   4., 18.29, -0., 'Homes', 'Medium'),
       ('FY25',  165.98360465,   1., 18.28, -0., 'Homes', 'Medium'),
       ('FY20',  138.109268  ,  nan, 14.66, nan, 'Businesses', 'Medium'),
       ('FY21',  177.62289562,  28., 13.77, -6., 'Businesses', 'Medium'),
       ('FY22',  191.98288414,   8., 13.46, -2., 'Businesses', 'Medium'),
       ('FY23',  200.26400951,   4., 13.31, -1., 'Businesses', 'Medium'),
       ('FY24',  203.82459332,   2., 13.31,  0., 'Businesses', 'Medium'),
       ('FY25',  205.18283926,   1., 13.31,  0., 'Businesses', 'Medium')],
      dtype=[('FY', 'O'), ('ADV', '<f8'), ('YoY_ADV', '<f8'), ('Yield', '<f8'), ('YoY_Yld', '<f8'), ('Cut', 'O'), ('Product', 'O')])

df = pd.DataFrame(a)
df1=pd.melt(df, id_vars=['FY','Product','Cut'], var_name="Metric", value_name="Value")
df2 = pd.pivot(df1, index=['Metric', 'Product','Cut'],columns=['FY'],values=['Value'])
df2

看起来像这样:

我想应用表格样式,以便可以将精美的表格复制/粘贴到 PowerPoint 中,但需要以下内容:

  1. 阴影列 23 财年、24 财年、25 财年橙色
  2. 应用格式:Metric=ADV 舍入到小数点零位,Metric=Yield 舍入到2 个小数点,YoY_ADV 加上 YoY_Yld 分别为 1小数位
  3. 负数为红色,否则为黑色
  4. 在桌子周围应用框架

这是我的代码,但我收到错误“无法使用多维键索引”:

    # 1. If numbers are negative, make red otherwise black
#####################################################
def color_negative_red(x):
    if x < 0:
      return 'color: red'
    else: 
      return 'color: black'

# 2. Slide major metrics so formatting can be applied
######################################################
adv_slice=df2.loc[('ADV', slice(None)), :]
yld_slice=df2.loc[('Yield', slice(None)), :]
yoy_adv_slice=df2.loc[('YoY_ADV', slice(None)), :]
yoy_yld_slice=df2.loc[('YoY_Yld', slice(None)), :]

#3. Apply table style  
#####################
df2.style.applymap(color_negative_red).set_properties(**{'background-color': 'orange'}, subset=['FY23','FY24','FY25']).format('{:.0f}', subset=adv_slice, na_rep='-').format('{:.2f}', subset=yld_slice, na_rep='-').format('{:.1f}', subset=(yoy_adv_slice,yoy_yld_slice), na_rep='-').set_table_styles([{'selector': '',
                    'props' : [('border','1px solid black')]},
                  {'selector': 'th',
                    'props' : [('border','1px solid black')]},
                  {'selector': 'td',
                    'props' : [('border','1px solid black')]}]).set_properties(**{'text-align': 'center'})

需要什么才能使代码正常工作?

【问题讨论】:

    标签: dataframe formatting pivot


    【解决方案1】:

    有一些模组:

        [![# 1. If numbers are negative, make red otherwise black
    #####################################################
    def color_negative_red(x):
        if x < 0:
          return 'color: red'
        else: 
          return 'color: black'
    
    #2. Apply table style  
    #####################
    df2.style.applymap(color_negative_red).set_properties(**{'background-color': 'orange'}, subset=\['FY23','FY24','FY25'\]).\
                     format('{:.0f}', subset=('ADV',), na_rep='-').\
                     format('{:.2f}', subset=('Yield',), na_rep='-').\
                     format('{:.1f}', subset=('YoY_ADV',), na_rep='-').\
                     format('{:.1f}', subset=('YoY_Yld',), na_rep='-').\
                     set_table_styles(\[{'selector': '',
                        'props' : \[('border','0.1px solid black')\]},
                      {'selector': 'th',
                        'props' : \[('border','0.5px solid black')\]},
                      {'selector': 'td',
                        'props' : \[('border','0.5px solid black')\]}\]).set_properties(**{'text-align': 'center'})][1]][1]
    

    【讨论】:

      猜你喜欢
      • 2021-06-24
      • 1970-01-01
      • 2018-08-29
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多