【发布时间】: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