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 worksdf.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?