Pandas风格突出显示对角线和非对角线元素

2024-10-03 11:26:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在风格上突出熊猫的主要对角线和相反的主要对角线元素 数据帧

我看到了这个链接:Pandas style: How to highlight diagonal elements

这显示了如何突出主对角线,但我想知道如何突出两个对角线与 两种不同的颜色

这是我的数据框:


import numpy as np
import pandas as pd


df = pd.DataFrame(data={'pred0': [10,   4],
                   'pred1': [0,   0],
            'total': [10,  4]},index=['true0','true1']
                   )

print(df)
       pred0  pred1  total
true0     10      0     10
true1      4      0      4

我的尝试

# Credit: ALLOLZ
def highlight_diag(df):
    a = np.full(df.shape, '', dtype='<U24')
    np.fill_diagonal(a, 'background-color: yellow')
    return pd.DataFrame(a, index=df.index, columns=df.columns)

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

但这只会高亮显示一条对角线,而不会高亮显示另一条对角线。 如何突出显示两条对角线

必需的

          pred0          pred1         total
true0     10(green)      0(red)     10(no highlight)
true1      4(red)      0(green)      4(no highlight)

蒂伊


Tags: 数据importdfindexstylenptotalpd
1条回答
网友
1楼 · 发布于 2024-10-03 11:26:42

这就是你想要的

import numpy as np
import pandas as pd

def highlight_diags(data):
    attr1 = 'background-color: lightgreen'
    attr2 = 'background-color: salmon'

    df_style = data.replace(data, '')
    np.fill_diagonal(df_style.values, attr1)
    np.fill_diagonal(np.flipud(df_style), attr2) 
    return df_style

df = pd.DataFrame(data={'pred0': [10,   4],
                   'pred1': [0,   0],
            'total': [10,  4]},index=['true0','true1']
                   )

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

enter image description here

相关问题 更多 >