1

是否可以在列名中添加背景颜色,同时根据单独的条件更改单元格背景颜色?

我目前能够根据条件突出显示单元格,但不确定如何为列名添加背景颜色:

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

无法弄清楚如何突出显示列名

期望的结果:

期望的结果

参考文献: 1 2

4

1 回答 1

0

您可以在您的 pandas 样式对象上使用applymap(mapperFunc, subset=[ColOfInterest]),它会为 pandas 数据框中的每个值调用 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)

输出

在此处输入图像描述

于 2021-09-20T20:49:11.197 回答