6

I have been struggling with how to style highlight pandas rows based on index names. I know how to highlight selected rows but when I have to highlight based on the index, the code is not working.

Setup

df = pd.DataFrame({'key': list('ABCD'), 'value': range(4)})
print(df)
  key  value
0   A      0
1   B      1
2   C      2
3   D      3

Highlight rows when key has value 'B' or 'D'

# this works

    df.style.apply(lambda x: ['background: lightgreen' 
                                          if (x.key == 'B' or x.key == 'D')
                                      else '' for i in x], axis=1)

Highlight rows based on index names

# This DOES NOT work
df1 = df.set_index('key')
df1.style.apply(lambda x: ['background: lightgreen' 
                                      if (x.index == 'B' or x.index == 'D')
                                      else '' for i in x], axis=1)

How to highlight the rows based on index names?

1 Answer 1

13

Change index to name:

df1.style.apply(lambda x: ['background: lightgreen' 
                                  if (x.name == 'B' or x.name == 'D')
                                  else '' for i in x], axis=1)

pic

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

2 Comments

What to do when we have a column called 'name' ?
@astro123 - then select by x['name']

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.