python - 如何将 pandas 样式应用于多列

标签 python pandas pandas-styles

我有以下数据框:

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]

列表:['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))

enter image description here

________________

▶️更新

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

关于python - 如何将 pandas 样式应用于多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67200699/

相关文章:

python - Raspbian Cronjob 不会被触发

python - 使用 python mechanize 和具有随机代理支持的 urllib2

python - Pandas/Python - 使用 stack() groupby() 和 apply() 的性能非常慢

Python Pandas 多条件赋值

python - 如何将 wxPython 用于 Python 3?

python - Pandas Dataframe 列平均值的 bool 运算 - 这必须很简单

python - 如何只提取括号之间的字符串部分?

python - 此条件的 Pandas DataFrame 样式

python - 如何使用 Pandas 样式器根据给定列为整行着色?

python - Pandas 样式 `.render()` - 显示前后的不同值