pandas 中的С条件颜色格式 [英] Сonditional color formatting in Pandas

查看:0
本文介绍了 pandas 中的С条件颜色格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

条件格式中的任务(我想是使用样式) 巨蟒, pandas

有一个有两列的盘子

应突出显示第二个表 条件:

  1. 如果第一个列数超过第二个列数,则为绿色;
  2. 如果第一个列数等于第二个列数,则为黄色;
  3. 如果第一个列数小于第二个列数,则为红色。[

谢谢您的帮助!

推荐答案的想法是使用Styler.apply创建新的按条件填充样式的DataFrame,用于按条件设置行DataFrame.mask
def highlight(x):
    c1 = 'background-color: green'
    c2 = 'background-color: yellow'
    c3 = 'background-color: red'

    m1 = x.iloc[:, 0] > x.iloc[:, 1]
    m2 = x.iloc[:, 0] == x.iloc[:, 1]

    df1 = pd.DataFrame(c3, index=x.index, columns=x.columns)
    return df1.mask(m1, c1).mask(m2, c2)

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

编辑:

如果只需要设置一列,请使用numpy.select

def highlight(x):
    c1 = 'background-color: green'
    c2 = 'background-color: yellow'
    c3 = 'background-color: red'
    c = ''

    m1 = x.iloc[:, 0] > x.iloc[:, 1]
    m2 = x.iloc[:, 0] == x.iloc[:, 1]

    df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
    df1.iloc[:, 1] = np.select([m1, m2], [c1, c2], default=c3)
    return df1

这篇关于 pandas 中的С条件颜色格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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