Pandas highlight rows based on index name

烂漫一生 提交于 2020-02-24 15:12:14

问题


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:


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)



来源:https://stackoverflow.com/questions/55574520/pandas-highlight-rows-based-on-index-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!