2

I have the following dataframe:

df=pd.DataFrame({'c1':['a','b','c'],
                 'c2':['aa', 'bb','cc'] })

And I have the following function to color cells:

def color_cell(cell, c):
    if cell in c:
        return "background-color: yellow"
    else:
        return ""

I want to use this function to color different columns of the dataframe.
For each column there is different c.

I try this:

cols=['c1', 'c2']
    
c1=['a']
c2=['aa', 'bb']
c= [c1, c2]
    
for i in range(0, 2):           
    html = (df.style
            .applymap(color_cell, 
                      c=c[i],                       
                      subset = cols[i])
            .render()
           )
(HTML(html))

Obviously, this doesn't work because only the result from the last iteration is returned.

What should I do to get all the columns colored?

1 Answer 1

4

I think it is better to make a list of target elements and pass them on to method parameters than to process them with for loop.

Get target list

c1= ['a']
c2= ['aa', 'bb']
c= [c1, c2]

slist = [st for row in c for st in row]

slist: ['a', 'aa', 'bb']


Method

def highlight_cols(s, cells):
    color = 'yellow' if s in cells else 'gray'
    return 'background-color: % s' % color

html = (df.style.applymap(highlight_cols, cells=slist).render())

Result

display(df.style.applymap(highlight_cols, cells=slist))

enter image description here

________________

▶️ Update

import pandas as pd

df=pd.DataFrame({'c1':['a','b','c', 'd'],
                 'c2':['a', 'aa', 'bb','cc'] })

# Specifies the style of the dataframe as a variable
df_style = df.style

def color_cell(cell, c):
    if cell in c:
        return "background-color: yellow"
    else:
        return ""

cols=['c1', 'c2']
c1=['a']
c2=['aa', 'bb']
c= [c1, c2]

# Use the newly specified variable 'df_style' instead of 'df.style'
for i in range(0, 2):           
    html = (df_style.applymap(color_cell, c=c[i], subset = cols[i]).render())

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer. However, this won't work because maybe in the column c2 there is an 'a' which I don't want to be colored.
@Ani I overlooked that there could be equal values. I revised it again, so please check it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.