【问题标题】:Python Pandas styling changing background color of whole row based on value in columnPython Pandas样式根据列中的值改变整行的背景颜色
【发布时间】:2020-02-24 17:57:45
【问题描述】:

我想根据下面的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,但它往往适用于整个表格。有没有办法修改此功能并应用于一列并更改所有行的背景?

输出应如下所示:

最终我将使用它来发送电子邮件。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    由于您使用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)
    

    输出:

    【讨论】:

    • 太棒了。这正是我所需要的。感谢您的宝贵时间。
    • 最后一个问题。如何将其转换为 html 以通过电子邮件发送?当我做df.style.apply(highlight, axis=1).to_html() 我得到错误
    • .render链接它?
    猜你喜欢
    • 2015-10-13
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多