是否可以在列名中添加背景颜色,同时根据单独的条件更改单元格背景色?
我目前能够根据条件高亮显示单元格,但不确定如何向列名中添加背景颜色:
# create dataframe
import pandas as pd
data = {'Cuisine':['Italian','Indian','Nepalese','Mexican', 'Thai'],
'Geographic Location':['Europe','Asia','Asia','N.America','Asia']}
df = pd.DataFrame(data) print(df)
Cuisine Geographic Location
0 Italian Europe
1 Indian Asia
2 Nepalese Asia
3 Mexican N.America
4 Thai Asia
# highlight cells based on condition
def highlight_Asia(x):
return ['background-color: GreenYellow' if v =='Asia' else '' for v in x]
df.style.apply(highlight_Asia)

# highlight column names
def highlight_header(x):
y= ['background-color: LightSkyBlue' for v in list(x)]
return y
df.style.apply(highlight_header)

预期结果:

发布于 2021-09-20 20:49:11
您可以在您的熊猫样式对象上使用applymap( mapperFunc,subset=ColOfInterest),它将为熊猫数据中的每个值调用mapperFunc,并传递传递的值,还可以使用子集参数传递选择性列。
示例代码:
def color_me(percentage):
color = 'green'
if percentage < 40:
color = 'red'
return 'background-color: %s' % color
import pandas as pd
df = pd.DataFrame({'Marks' : range(0,101,20)})
df.style.applymap(color_me)输出

https://stackoverflow.com/questions/53162898
复制相似问题