Pandas 风格:在整行上绘制边框,包括多索引

Lut*_*utz 5 python pandas jupyter-notebook pandas-styles

我在 jupyter 笔记本中使用 pandas 样式来强调此数据框中子组之间的边界:

(从技术上讲:在每个更改的多重索引处绘制边框,但忽略最低级别)

# some sample df with multiindex
res = np.repeat(["response1","response2","response3","response4"], 4)
mod = ["model1", "model2","model3","model4"]*len(res)
data = np.random.randint(0,50,size=len(mod))
df = pd.DataFrame(zip(res,mod,data), columns=["res","mod","data"])
df.set_index(["res","mod"], inplace=True)

# set borders at individual frequency
indices_with_borders = range(0,len(df), len(np.unique(mod)))
df.style.set_properties(subset=(df.index[indices_with_borders], df.columns), **{
                      'border-width': '1px', "border-top-style":"solid"}) 
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

现在看起来有点傻,边框只绘制在列上,而不是一直贯穿多重索引。这将是一种更令人愉悦的风格:

在此输入图像描述

有谁知道如何/是否可以实现?提前致谢!

Att*_*k68 5

s = df.style
for l0 in ['response1', 'response2', 'response3', 'response4']:
    s.set_table_styles({(l0, 'model4'): [{'selector': '', 'props': 'border-bottom: 3px solid red;'}],
                        (l0, 'model1'): [{'selector': '.level0', 'props': 'border-bottom: 3px solid green'}]},
                      overwrite=False, axis=1)
s
Run Code Online (Sandbox Code Playgroud)

由于多索引会稀疏并跨越行,因此您需要稍微小心地控制行类。这有点痛苦,但它满足了你的需要......

在此输入图像描述