Pandas Styling (background + font) based on String data - Is there a better way?

Viewed 815

Can i combine the lambda func for background color and the lambda func for font color into a single lamdba func? This will be used for a very large dataframe with plenty of different styling, so it would be nice to reduce the code in half.

Any other suggestions for a better way are welcomed

# raw data
df = pd.DataFrame({'Name':['name1', 'name2', 'name3', 'name1', 'name2', 'name3', 'name1', 'name2', 'name3' ],  
                   'Rotation':['ER','PEDI','MAM','PEDI', 'ERJD','PEDI','JMAM','ERSN','ABD']})

#style
df = df.style.apply(lambda x: ["background-color: green" if 'ER' in v else "" for v in x], axis = 1)\
             .apply(lambda x: ["color: orange" if 'ER' in v else "" for v in x], axis = 1)\
             .apply(lambda x: ["background-color: red" if 'MAM' in v else "" for v in x], axis = 1)\
             .apply(lambda x: ["color: yellow" if 'MAM' in v else "" for v in x], axis = 1)

resulting df shown below:

styled df

1 Answers

I'd do something like this (Python 3.6+ for f-strings):

def where(x):
  bg = ['green', 'red']
  fg = ['orange', 'yellow']
  ls = ['ER', 'MAM']
  for i, y in enumerate(ls):
    if y in x:
      return f"background-color: {bg[i]}; color: {fg[i]}"
  return ''

df.style.applymap(where)
Related