I have the following pandas df
Player Team EPA
0 L.Jackson BAL 0.33
1 P.Mahomes KC 0.25
2 D.Brees NO 0.24
3 M.Stafford DET 0.21
4 D.Prescott DAL 0.19
5 R.Tannehill TEN 0.18
That I want to style using the colors by applying the following dictionary values, where the keys match the Team
field. I would also like to make the corresponding values of the Player
field the same color.
COLORS = {'BAL':'#241773','DAL':'#B0B7BC','DET':'#046EB4',
'KC':'#CA2430','NO':'#A08A58','TEN':'#4095D1'}
I tried looking at this question and had no success with the following code
def highlight_cols(s, coldict):
if qbs.Team in COLORS.keys():
return ['background-color: {}'.format(COLORS[qbs.Team])] * len(s)
return [''] * len(s)
qbs.style.apply(highlight_cols, coldict=COLORS)
I have been reading through the DataFrame.style
documentation and have been trying to figure out a way where I can color each Team
value corresponding with the hexcode in the dictionary. In cells 5 and 6 of the notebook in the documentation, it shows how you can write a function and use df.style.applymap()
to apply a function, but I'm not entirely sure how to go about this specific function. I tried using a .loc
to no avail. Any help is appreciated. Thanks!
Not sure if you just want the EPA column colored, if you want the entire row remove the subset
argument from the last line.
def highlight_cols(s, coldict):
return ['background-color: {}'.format(COLORS[v]) if v else '' for v in qbs.Team.isin(COLORS.keys())*qbs.Team.values]
qbs.style.apply(highlight_cols, coldict=COLORS, subset='EPA')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.