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

Python根据列中的值更改整行背景色的样式,python,pandas,Python,Pandas,我想根据下面的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:

我想根据下面的
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}})
数据:

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

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'
def突出显示:
'''
以黄色系列突出显示最大值。
'''
如果s 14和s<30):
返回“背景色:黄色”
如果s>30:
返回“背景色:红色”
我正在努力申请testdf。我可以使用
testdf.style.apply
,但它倾向于应用于整个表。是否有办法修改此函数并应用于一列并更改所有行的背景

输出应如下所示:

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'


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

因为您使用
lastupdate
来确定整行,所以您希望
对行应用
,并返回每个单元格的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)
def高亮显示(行):
'''
以黄色系列突出显示最大值。
'''
s=行['lastupdate']

如果由于使用了
lastupdate
来确定整行,因此需要对行应用
并返回每个单元格的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)
def高亮显示(行):
'''
以黄色系列突出显示最大值。
'''
s=行['lastupdate']

如果那太棒了。这正是我需要的。谢谢你的时间。最后一个问题。如何将其转换为html以通过电子邮件发送?当我执行
df.style.apply(高亮显示,轴=1)到_html()
时,我会得到错误链接,并使用
.render
?太棒了。这正是我需要的。谢谢你的时间。最后一个问题。如何将其转换为html以通过电子邮件发送?当我执行
df.style.apply(高亮显示,轴=1)到_html()
时,我得到了错误链接
。渲染