I am trying to style a very large dataframe with many different color combinations for cell fill and font. I experimented using lambda functions, but seemed like a very inefficient way of doing the styling. I'm looking for a solution similar to the example shown at the bottom of the post, labeled "Desired Approach".
My specific case involves a dictionary of lists. Here is an example dataset...i'd like to color all the names of males blue/orange and all the names of females pink/red:
# raw data
df = pd.DataFrame({'Freshman':['Mike', 'Bill', 'Maria'],
'Junior':['Lauren','Tom','Jessica'],
'Senior':['Sandy','Michelle','Mike']
})
my_dict = {'Male':['Mike','Bill','Tom'],
'Female':['Maria','Lauren','Jessica','Sandy','Michelle']}
Desired Approach:
I tried tweaking this approach for my use-case, but cant get it to work.
# 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']})
def where(x):
bg = ['blue', 'pink']
fg = ['orange', 'red']
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)
this code returns the following: