首页 > 解决方案 > Pandas 中的条件颜色格式

问题描述

条件格式中的任务(我猜使用样式)Python,Pandas

有一个有两列的板

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

  1. 如果第一列数字超过第二列,则为绿色;
  2. 如果第一列编号等于第二列,则为黄色;
  3. 如果第一列编号小于第二列,则为红色。[在此处输入图像描述

谢谢你的帮助!

标签: pythonpandasstyling

解决方案


想法是创建新的 DataFrame,由条件填充样式,使用条件Styler.apply设置行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

推荐阅读