基于某些条件的彩色数据框 [英] Color dataframe based on some condition

查看:82
本文介绍了基于某些条件的彩色数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  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_3 col_4 (如果值小于列 LL 或更高)而不是每行 UL



如果较低,则将其涂成红色。



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



谢谢!



结果可能像这样

解决方案

LL UL 列,并返回由


I would like to color the dataframe based on the condition below

   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

I want to color col_1 col_2 col_3 and col_4 if the values is lower than column LL or higher than UL in each row.

If lower, color it red. If higher, color it green.

Moreover, if there is no upper limit and no lower limit, do nothing in that row.

Thanks!

The results may look like this

解决方案

Compare all columns by LL and UL columns and return style DataFrame filled by numpy.select:

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)

这篇关于基于某些条件的彩色数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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