如何将 pandas 样式应用于多列

How to apply pandas style to multiple columns

我有以下数据框:

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

而且我有以下功能可以给单元格上色:

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

我想使用此函数为数据框的不同列着色。
对于每一列都有不同的 c.

我试试这个:

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))

显然,这不起作用,因为只返回上次迭代的结果。

我应该怎么做才能使所有列都着色?

我认为制作一个目标元素列表并将它们传递给方法参数比用for循环处理它们更好。

获取目标列表

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

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

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


方法

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())

结果

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

________________

▶️更新

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())