Pandas highlight rows based on index name

时间:2019-04-08 13:23:14

标签: python pandas pandas-styles

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 个答案:

答案 0 :(得分:4)

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