【问题标题】:Style specific rows in multiindex dataframe多索引数据框中的样式特定行
【发布时间】:2023-02-17 15:03:59
【问题描述】:

我有一个看起来像的熊猫数据框:

Year                          2019                   2020               
Decision                   Applied Admitted     % Applied Admitted     %
Class         Residency                                                 
Freshmen      Resident      1143.0    918.0  80.3  1094.0   1003.0  91.7
              Non-Resident  1371.0   1048.0  76.4  1223.0   1090.0  89.1
              Total         2514.0   1966.0  78.2  2317.0   2093.0  90.3
Transfer      Resident       404.0    358.0  88.6   406.0    354.0  87.2
              Non-Resident   371.0    313.0  84.4   356.0    288.0  80.9
              Total          775.0    671.0  86.6   762.0    642.0  84.3
Grad/Postbacc Total          418.0    311.0  74.4   374.0    282.0  75.4
Grand         Total         3707.0   2948.0  79.5  3453.0   3017.0  87.4

注意:完整的 MWE 在 this 问题中。

我正在尝试以不依赖于实际行号的方式将总行(这里是第 3、6、7、8 行)加粗并加粗总计行(第 8 行)。

我可以这样做:

df_totals.style.apply(lambda x:["font-style: italic;"]*len(x),subset=((slice(None),"Total"),))\
               .applymap_index(lambda x:"font-style: italic;" if x in ("Grand","Total") else "")

对我来说,这似乎超级不符合 Python 规范、丑陋且无法维护,尤其是对 applymap_index 的调用。有没有更流畅的方法来做到这一点?

【问题讨论】:

    标签: pandas multi-index styling


    【解决方案1】:

    第一部分应该简化,我认为第二部分很好,style.Styler.applymap_index 中的示例只有很小的变化:

    df_totals.style.set_properties(**{'font-style': 'italic'}, subset=((slice(None),"Total")))
             .applymap_index(lambda x:"font-style: italic;" if x in ("Grand","Total") else None)
    

    【讨论】:

      猜你喜欢
      • 2022-11-28
      • 2022-07-08
      • 2020-10-23
      • 2017-01-12
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 2021-10-03
      相关资源
      最近更新 更多