我想根据以下条件为数据框着色
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
着色每行中 LLUL
。
如果较低,则将其涂成红色。如果更高,则将其着色为绿色。
此外,如果没有上限和下限,则该行不执行任何操作。
谢谢!
最佳答案
按 LL
和 UL
列比较所有列,并返回由 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)
关于python - 基于某些条件的颜色数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56784411/