根据条件为 pandas 造型 [英] Styling pandas based on conditions

查看:63
本文介绍了根据条件为 pandas 造型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据条件为文本或数据框的单元格上色.这是我的代码.它的工作原理:

I am trying to color the text or cells of data frame based on the condition. This is the code I have. It works:

def Highlight_Majors(val):

    color = 'blue' if val == "Austria" else 'black'
    return 'color: %s' % color

s = df.style.applymap(Highlight_Majors)
s

字符串奥地利"现在在数据框中突出显示. 如果我需要突出多个国家怎么办?

The string "Austria" now appears highlighted in the dataframe. What if I have more than one countries I need to highlight?

这不起作用:

def Highlight_Majors(val):

    color = 'blue' if val == "Austria"|"Belgium" else 'black'
    return 'color: %s' % color

正确的方法是什么?

推荐答案

使用in运算符进行设置的成员资格测试:

Use the in operator with a set membership test:

def Highlight_Majors(val):
    return 'color: %s' % ('blue' if val in {"Austria", "Belgium"} else 'black')

这篇关于根据条件为 pandas 造型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆