首页 > 解决方案 > How to style the first index in a multi-index DataFrame

问题描述

I have the following DataFrame:

                Cluster 0 (N=1286)
a   bmi         28.21 (25.01, 30.48)
    gender (f)  67 (5.21%)
b   APACHE      17.75 (15.0, 21.0)
    ASTP        4.66 (3.0, 7.0)
    age         62.92 (57.0, 72.0)

Code for this DataFrame:

df = pd.DataFrame( {'Cluster 0 (N=1286)': {('a', 'gender (f)'): '67 (5.21%)', ('a', 'bmi'): '28.21 (25.01, 30.48)', ('b', 'age'): '62.92 (57.0, 72.0)', ('b', 'ASTP'): '4.66 (3.0, 7.0)', ('b', 'APACHE'): '17.75 (15.0, 21.0)'}})

The DataFrame has two indices: a and b on the first level, and 'bmi', 'gender', ..., on the second level. Normally, a DataFrame alternates the background-color of the rows with white/light grey. I want to change this so that the a/b levels alternate with background colors white/light grey.

It should look like this:

enter image description here

标签: pythonpandas

解决方案


你可以试试这个:

def color(x):
    return [
        "background-color: lightgrey" if df.index[i][0] == "b" else ""
        for i in range(0, len(df))
    ]

df.style.apply(func=color, axis=0)
# If you run the code in a Jupyter cell, it outputs
# the dataframe with lines "b" greyed.

请注意,根据Pandas 文档“您只能设置值的样式,而不能设置索引或列的样式”


推荐阅读