python - Pandas 中的条件颜色格式

标签 python pandas styling

条件格式任务(我猜使用样式) Python、 Pandas

有一个有两列的盘子

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

  1. 如果第一列数超过第二列,则呈绿色;
  2. 如果第一列数等于第二列数,则为黄色;
  3. 如果第一列数小于第二列数,则显示为红色。[ enter image description here

感谢您的帮助!

最佳答案

想法是创建新的 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

关于python - Pandas 中的条件颜色格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56901393/

相关文章:

python - Pandas GroupBy 均值

jquery - 适用于所有屏幕尺寸的 HTML 前端

python - TabPy - 无效的文件路径或缓冲区对象类型

python - 在 google colab 中运行 python 脚本,nohup 给出 ImportError

python - 字典中的元组

html - <a> 按钮的位置不固定其位置

html - 什么元素阻止我的宽度属性应用于我的选项卡?

python - 在嵌套字典中查找最大值时出现 KeyError

python - 从 resources.qrc 文件创建 QIcon

python - 使用 pandas 从开始时间和持续时间(分钟)计算结束时间。标准方法错误