如何根据特定条件将背景色应用于熊猫数据框

时间:2020-07-01 19:56:45

标签: python pandas dataframe pandas-styles

我一直在尝试根据条件(如果元素与列表中存在的值匹配)将背景色添加到数据框。我找到了一种根据条件更改文本颜色的方法,但找不到替代方法来更改背景颜色。

我正在使用的代码如下:


#lists
removed_list = ['Blah Blah', 'BlahBlah2', 'BlahBlah3']
added_list = ['Service Fee']

#method to color-code based on condition
def color_negative_red(value):

  if value in removed_list:
    color = 'red'
  elif value in added_list:
    color = 'blue'
  else:
    color = ''

  return 'color: %s' % color

final_df = df.style.applymap(color_negative_red)

现在,当我打印final_df时,我得到:

The column names from "removed_list" are coded RED and columns from "added_list" are coded BLUE, while all other columns are default

我要做的是,我不想改变文本的颜色,而是要向数据框中的上述突出显示的值添加背景颜色。

请帮助!

0 个答案:

没有答案