Search code examples
pythonpandaspandas-styles

Pandas style: How to highlight diagonal elements


I was wondering how to highlight diagonal elements of pandas dataframe using df.style method.

I found this official link where they discuss how to highlight maximum value, but I am having difficulty creating function to highlight the diagonal elements.

Here is an example:

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_max(s):
    '''
    highlight the maximum in a Series yellow.
    '''
    is_max = s == s.max()
    return ['background-color: yellow' if v else '' for v in is_max]

df.style.apply(highlight_max)

This gives following output: enter image description here

I am wanting a yellow highlight across the diagonal elements 1,3,7,11 only.

How to do that?


Solution

  • 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)