我有以下数据框:
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))
________________
▶️更新
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())
关于python - 如何将 pandas 样式应用于多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67200699/