根据多索引数据透视表中同一行中的不同单元格突出显示不同的单元格 table

Highlight distinct cells based on a different cell in the same row in a multiindex pivot table

我创建了一个枢轴 table,其中列 headers 有多个级别。这是一个简化版本:

index = ['Person 1', 'Person 2', 'Person 3']
columns = [
    ["condition 1", "condition 1", "condition 1", "condition 2", "condition 2", "condition 2"],
    ["Mean", "SD", "n", "Mean", "SD", "n"],
]
data = [
    [100, 10, 3, 200, 12, 5],
    [500, 20, 4, 750, 6, 6],
    [1000, 30, 5, None, None, None],
]
df = pd.DataFrame(data, columns=columns)

df

现在,如果 SD > 10,我想突出显示 SD 旁边的相邻单元格。它应该是这样的:

我找到了 但无法使其适用于多指数。

感谢您的帮助。

使用Styler.apply with custom function - for select column use DataFrame.xs and for repeat boolean use DataFrame.reindex:

def hightlight(x):
    c1 = 'background-color: red'

    mask = x.xs('SD', axis=1, level=1).gt(10)
    #DataFrame with same index and columns names as original filled empty strings
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    #modify values of df1 column by boolean mask
    return df1.mask(mask.reindex(x.columns, level=0, axis=1), c1)

df.style.apply(hightlight, axis=None)