How to use multiple background colors for different string value in a particular row of csv file

Viewed 28

I have CSV file with multiple columns and I am searching some string in column 5 and highlighting the row for diffrent string. As of now I am able to use just two colours but I want to use more colors for more string into it. Example for

     x['4']="abc" --->I want to use yellow color 
     x['4']="xyz" --->I want to use grey  color
     x['4']="pqr" --->I want to use green color  

For two color I am using

         n = len(df.columns) 
         df.style.apply(lambda x: ["background-color: red"]*n if x['4']== 'ERROR' else ["background-color: white"]*n, axis = 1)

What changes should we make for multiple colours

1 Answers

Create dictionary for background colors by values and pass to Styler.applymap for mapping by dict.get, if no match is returned empty value:

d = {'abc':'background-color:yellow',
     'xyz':'background-color:grey',
     'pqr':'background-color:green'}

df.style.applymap(lambda x: d.get(x,''), subset=['4'])

Another idea with Styler.apply and axis=1, for mapping use Series.map with replace missing values by Series.fillna:

df.style.apply(lambda x: x.map(d).fillna(''), subset=['4'], axis=1)

Sample data:

df = pd.DataFrame({'4':['abc','xyz','pqr','temp'],
                   '5':range(4)})

Test in jupyter notebook:

enter image description here

EDIT:

For coloring rows use custom function:

def hightlight(x):
    d = {'abc':'background-color:yellow',
         'xyz':'background-color:grey',
         'pqr':'background-color:green'}

    #DataFrame with same index and columns names as original filled repeated strings
    out = np.repeat(x['4'].map(d).fillna('').to_numpy(), len(x.columns)).reshape(x.shape)
    return pd.DataFrame(out, index=x.index, columns=x.columns)

df.style.apply(hightlight, axis=None)
Related