python - 使用 pandas 样式功能更改多级索引字体

标签 python pandas crosstab

我想制作一些带有多级索引的漂亮表格(跨多个变量交叉制表)。根据下面的数据,placebandstatus 的索引相当大,如果我用 pandas 风格的函数打印它,它们是负责的。有没有办法改变多级标题的大小/颜色/字体?非常感谢提前

df1 = pd.DataFrame(data={'id': [1,2,3,4,5,6,7,8,9,10], 'place': [1,1,2,2,2,1,1,2,1,1], 'band': [1,2,3,3,3,2,1,2,3,1], 'status': [1,2,2,1,1,1,1,2,1,2]})

d1={1: 'north', 2: 'south'} 
d2={1: '10-20', 2: '30-40', 3: '20-30'} 
d3={1: 'green', 2: 'red'} 

df1['place']=df1['place'].map(d1).fillna('Other')
df1['band']=df1['band'].map(d2).fillna('Other')
df1['status']=df1['status'].map(d3).fillna('Other')

tab = pd.crosstab(df1.band, [df1.place, df1.status]).apply(lambda r: r/r.sum(), axis=1).round(2) 

tab.style

最佳答案

您无法装饰多索引中的单个索引,但可以对批量采用以下方法。

th_css = [
    {
        "selector": "th",
        "props": [
            ("background-color", "#48d1cc"),
            ("color", "white"),
            ("border", "1px solid #fdf5e6"),
            ("font-size", "16px"),
        ],
    },
]
style = tab.style
style = style.set_precision(2).set_table_styles(th_css)
style

enter image description here

关于python - 使用 pandas 样式功能更改多级索引字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67884550/

相关文章:

crystal-reports - Crystal 报表交叉表

python - 无法强制脚本不在控制台中打印错误日志详细信息

python - readlines不读取python中文件的最后一行

python - Pandas 中的反向选择

python - 如何有条件地更新 Pandas 中的 DataFrame 列

python - 从行创建表

python - 如何使用 strftime 以正确的顺序绘制月份名称?

python - 将数据框转换为元组列表的字典

postgresql - postgres tablefunc crosstab() 函数中的类别可以是整数吗?

python - Pandas 从加入日期开始计算每天的事件数