Pandas style: How to highlight diagonal elements

Using axis=None we can use numpy to easily set the diagonal styles (Credit for this goes to @CJR)

import numpy as np
import pandas as pd

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)

enter image description here


Original, really hacky solution

a = np.full(df.shape, '', dtype='<U24')
np.fill_diagonal(a, 'background-color: yellow')
df_diag = pd.DataFrame(a,
                       index=df.index,
                       columns=df.columns)

def highlight_diag(s, df_diag):
    return df_diag[s.name]

df.style.apply(highlight_diag, df_diag=df_diag)

The other answer is pretty good but I already wrote this so....

def style_diag(data):
    diag_mask = pd.DataFrame("", index=data.index, columns=data.columns)
    min_axis = min(diag_mask.shape)
    diag_mask.iloc[range(min_axis), range(min_axis)] = 'background-color: yellow'
    return diag_mask

df = pd.DataFrame({'a':[1,2,3,4],'b':[1,3,5,7],'c':[1,4,7,10],'d':[1,5,9,11]})
df.style.apply(style_diag, axis=None)

The trick is to use the axis=None parameter of the df.style.apply function in order to access the entire dataset:

import numpy as np
import pandas as pd

df = pd.DataFrame({'a':[1,2,3,4],'b':[1,3,5,7],'c':[1,4,7,10],'d':[1,5,9,11]})

def highlight_diag(data, color='yellow'):
    '''
    highlight the diag values in a DataFrame
    '''
    attr = 'background-color: {}'.format(color)
    # create a new dataframe of the same structure with default style value
    df_style = data.replace(data, '')
    # fill diagonal with highlight color
    np.fill_diagonal(df_style.values, attr)
    return df_style

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

output

Tags:

Python

Pandas