How to highlight row and column immediately in pandas

I can highlight a column using the syntax

import pandas as pd df = pd.DataFrame([[1,0],[0,1]]) df.style.apply(lambda x: ['background: lightblue' if x.name == 0 else '' for i in x]) 

enter image description here

Similarly, I can highlight a row by skipping axis=1 :

 df.style.apply(lambda x: ['background: lightgreen' if x.name == 0 else '' for i in x], axis=1) 

enter image description here

However, I cannot figure out how to do this at the same time; the problem is that when I use applymap , I get only the values, not the names of the series from which they come.

+7
source share
1 answer

How to do something like this? Enumerate the column and check the index when creating the style list:

 df.style.apply(lambda x: ['background: lightblue' if x.name == 0 or i == 0 else '' for i,_ in x.iteritems()]) 

enter image description here

Or if you have a color preference:

 df.style.apply(lambda x: [('background: lightblue' if x.name == 0 else ('background: lightgreen' if i == 0 else '')) for i,_ in x.iteritems()]) 

enter image description here

+7
source

Source: https://habr.com/ru/post/1011869/


All Articles