15

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 passing 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 can't work out how to do both at once; the problem is that when I use applymap, I only get the values, not the names of the series that they come from.

0

2 Answers 2

13

How about doing something like this? Enumerate the column and check the index while building up 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 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

Sign up to request clarification or add additional context in comments.

1 Comment

yeah this is the right way ... seems obvious now, just was having trouble wrapping me head around it for some reason!
3

You can also chain your styles:

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])\
.apply(lambda x: ['background: lightgreen' if x.name == 0 else '' for i in x], axis=1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.