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:
JavaScript
x
14
14
1
import numpy as np
2
import pandas as pd
3
4
df = pd.DataFrame({'a':[1,2,3,4],'b':[1,3,5,7],'c':[1,4,7,10],'d':[1,5,9,11]})
5
6
def highlight_max(s):
7
'''
8
highlight the maximum in a Series yellow.
9
'''
10
is_max = s == s.max()
11
return ['background-color: yellow' if v else '' for v in is_max]
12
13
df.style.apply(highlight_max)
14
I am wanting a yellow highlight across the diagonal elements 1,3,7,11 only.
How to do that?
Advertisement
Answer
The other answer is pretty good but I already wrote this so….
JavaScript
1
9
1
def style_diag(data):
2
diag_mask = pd.DataFrame("", index=data.index, columns=data.columns)
3
min_axis = min(diag_mask.shape)
4
diag_mask.iloc[range(min_axis), range(min_axis)] = 'background-color: yellow'
5
return diag_mask
6
7
df = pd.DataFrame({'a':[1,2,3,4],'b':[1,3,5,7],'c':[1,4,7,10],'d':[1,5,9,11]})
8
df.style.apply(style_diag, axis=None)
9