繁体   English   中英

根据另一个数据框中的列有条件地格式化每列中的单元格

[英]Conditionally format cells in each column based on columns in another dataframe

我有一个数据框,其中包含 20 多个元素的阈值,其格式如下

df1:

30 40 10
降低 10 5 1

我有另一个数据框,其中包含这些元素的值

df2:

示例 1 50.8 100 20
样本 2 -0.01 2 -1

如果 df2 中的值大于上限阈值,我希望 df2 中单元格的背景颜色在写入 Excel 文件时为红色。 如果该值低于下限阈值,我希望单元格为黄色。

所以在这个例子中,50.8 的背景颜色应该是红色,因为 50.8 > 30。

我之前在比较单个值时已经这样做了

df.style.apply(lambda x: 'background-color : red' if x>=value else '')

但是我迷失了如何根据 df1 中的列按列应用它

可以使用np.select比较数据np.select并设置条件的结果:

def bounded_highlights(df):
    conds = [df > df1.loc['Upper'], df < df1.loc['Lower']]
    labels = ['background-color:red', 'background-color: yellow']
    return np.select(conds, labels, default='')


df2.style.apply(bounded_highlights, axis=None)

风格化的 df2

DataFrames 和 Imports(稍微修改 df2 所以不是所有都突出显示):

import numpy as np
import pandas as pd


df1 = pd.DataFrame({'Li': {'Upper': 30, 'Lower': 10},
                    'Se': {'Upper': 40, 'Lower': 5},
                    'Be': {'Upper': 10, 'Lower': 1}})

df2 = pd.DataFrame({
    'Li': {'Sample 1': 50.8, 'Sample 2': -0.01},
    'Se': {'Sample 1': 100, 'Sample 2': 6},
    'Be': {'Sample 1': 9, 'Sample 2': -1}
})

修改后的df2

             Li   Se  Be
Sample 1  50.80  100   9
Sample 2  -0.01    6  -1

np.select代码如何工作:

conds = [df2 > df1.loc['Upper'], df2 < df1.loc['Lower']]
labels = ['background-color:red', 'background-color: yellow']
styles = np.select(conds, labels, default='')

conds

[             Li     Se     Be
Sample 1   True   True  False
Sample 2  False  False  False,
              Li     Se     Be
Sample 1  False  False  False
Sample 2   True  False   True]

根据condsTrue值应用styles标签:

[['background-color:red' 'background-color:red' '']
 ['background-color: yellow' '' 'background-color: yellow']]

您可以按照此处的建议进行操作: How to define color of specific cell in pandas dataframe based on integer position (eg, df.iloc[1,1]) with df.style? . 基本思想是制作一个你想要使用的样式的数据框,并应用它:

styles = pd.DataFrame('', index=df2.index, columns=df2.columns)
styles[df2 > df1.loc['Upper']] = 'background-color : red'
df2.style.apply(styles, axis=None)

这类似于@Henry Ecker 建议的内容,除了它不使用np.select ,而是手动应用条件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM