Ani
Ani

Reputation: 179

How to apply pandas style to multiple columns

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?

Upvotes: 2

Views: 2744

Answers (1)

elena.kim
elena.kim

Reputation: 958

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

Upvotes: 4

Related Questions