Conditionally formatting a column using a dictionary (Pandas)

Viewed 163

I've scoured the forums and am still struggling with this.

Say I have a dictionary of keys with html colours as values, i.e:

colours = {'a': '#2DB2EC',
           'b': '#A71AB7',
           'c': '#EB4141',
           'd': '#EB4141',
           'e': '#36D22C',
           'f': '#2C4ED2',
           'g': '#137C15',
           'h': '#F4EA06'}

I also have a dataframe with two columns, one of which (col1) corresponds to the keys in my "colours" dictionary:

col1     col2
a        900
d        1000
h        800
z        750
m        100
l        50

How do I use the Pandas style.applymap to colour-code the second column based on the dictionary value of column one (leaving it blank/white if no value found)? I've been playing around with some lambda functions but am having real difficulty in getting anything to work.

Sorry if this is a basic question and thanks in advance.

2 Answers

Try with:

df.style.apply(lambda r: [f"background-color:{colours.get(r['col1'],'')}"]*len(r), axis=1)

Output:

enter image description here

colour-code the second column based on the dictionary value of column one (leaving it blank/white if no value found)

You can also try series.map and then assign blank color to the col1 when done.

def col_fun(df_c):
    df_c = df_c.copy()
    df_c['col2'] = df_c['col1'].map(colours).fillna('').radd("background-color:")
    df_c['col1'] = 'background-color:'
    return df_c
df.style.apply(col_fun,axis=None)
#or if you have more cols: df.style.apply(col_fun,axis=None,subset=['col1','col2'])

enter image description here

Related