熊猫样式突出显示对角线和关闭对角线元素

时间:2019-10-14 17:44:31

标签: python pandas

我试图对熊猫的主要对角线元素和相对的主要对角线元素进行样式突出显示 数据框。

我看到了以下链接: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)

TIY。

1 个答案:

答案 0 :(得分:1)

这给出了您想要的

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