Python根据列中的值更改整行背景色的样式

2024-04-26 11:33:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据下面的lastupdate列将背景颜色更改为绿色、黄色和红色:

可复制代码:

testdf = pd.DataFrame({'title': {0: 'Test1',
  1: 'Test2',
  2: 'Test3',
  3: 'Test4',
  4: 'Test5',
  5: 'Test6',
  6: 'Test7',
  7: 'Test8'},
 'url': {0: 'link',
  1: 'link',
  2: 'link',
  3: 'link',
  4: 'link',
  5: 'link',
  6: 'link',
  7: 'link'},
 'status': {0: 'In_progress',
  1: 'In_progress',
  2: 'In_progress',
  3: 'In_progress',
  4: 'In_progress',
  5: 'In_progress',
  6: 'In_progress',
  7: 'In_progress'},
 'age': {0: 12, 1: 14, 2: 31, 3: 42, 4: 81, 5: 104, 6: 105, 7: 138},
 'lastupdate': {0: 6,
  1: 18,
  2: 20,
  3: 20,
  4: 20,
  5: 19,
  6: 90,
  7: 111}})

数据:

    title   url status  age lastupdate
0   Test1   link    In_progress 12  6
1   Test2   link    In_progress 14  18
2   Test3   link    In_progress 31  20
3   Test4   link    In_progress 42  20
4   Test5   link    In_progress 81  20
5   Test6   link    In_progress 104 19
6   Test7   link    In_progress 105 90
7   Test8   link    In_progress 138 111

绿色、黄色、红色的逻辑如下:

def highlight(s):
    '''
    highlight the maximum in a Series yellow.
    '''
    if s <= 14: 
        return 'background-color: green'
    elif (s > 14 & s < 30):
        return 'background-color: yellow'
    elif s > 30:
        return 'background-color: red'

我正在努力申请testdf。我可以使用testdf.style.apply,但它往往适用于整个表。是否有办法修改此函数并应用于一列并更改所有行的背景

输出应如下所示:

enter image description here

最终我会用它来发送电子邮件


Tags: inreturntitlelinkcolorbackground背景progress
1条回答
网友
1楼 · 发布于 2024-04-26 11:33:42

由于您使用lastupdate来确定整行,因此您希望在行上apply并返回每个单元格的css格式。大概是这样的:

def highlight(row):
    '''
    highlight the maximum in a Series yellow.
    '''
    s = row['lastupdate']
    if s <= 14: 
        css = 'background-color: green'
    elif (14 < s < 30):
        css = 'background-color: yellow'
    else:
        css = 'background-color: red'

    return [css] * len(row)

df.style.apply(highlight, axis=1)

输出:

enter image description here

相关问题 更多 >