python - 基于某些条件的颜色数据框

标签 python pandas colors

我想根据以下条件为数据框着色

   LL    UL   col_1   col_2   col_3   col_4 
1   0    10     5       -6      13      46
2   3    12     0        5       8      55
3 NaN   NaN    -9        8       4       5

如果值低于 列,我想为 col_1 col_2 col_3col_4 着色每行中 LL 或高于 UL

如果较低,则将其涂成红色。如果更高,则将其着色为绿色。

此外,如果没有上限和下限,则该行不执行任何操作。

谢谢!

结果可能如下所示 enter image description here

最佳答案

LLUL 列比较所有列,并返回由 numpy.select 填充的样式 DataFrame :

def highlight(x):
    c1 = 'background-color: red'
    c2 = 'background-color: green'
    c3 = '' 
    m1 = x.lt(x['LL'], axis=0)
    m2 = x.gt(x['UL'], axis=0)
    #if necessary set first 2 columns to False
    m1.iloc[:, :2] = False
    m2.iloc[:, :2] = False

    out = np.select([m1, m2], [c1, c2], default=c3)
    return pd.DataFrame(out, index=x.index, columns=x.columns)

df.style.apply(highlight, axis=None)
<小时/>
df.style.apply(highlight, axis=None).to_excel('file.xlsx', index=False)

pic

关于python - 基于某些条件的颜色数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56784411/

相关文章:

Python 单元测试未运行

python - 如何使用 Python 中的调查权重计算 OLS 回归。

python - pd.Serie 每行的平均值 "score"基于通过另一个分数系列映射的内容

Python 子进程 : Issues capturing error where part of command fail when piped together

python - 从对象列表构建数据帧花费的时间太长

python - 加速数据帧循环

python - 在 Pandas 中按年/月/日分组

cocoa - 如何设置 Cocoa 工具提示的文本颜色?

HTML 文件的 Eclipse 语法颜色

c# - 2种以上颜色混色