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

时间:2021-07-20 18:04:27

标签: python excel pandas pandas-styles

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

df1:

<头>
Se 成为
30 40 10
10 5 1

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

df2:

<头>
Se 成为
示例 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 中的列按列应用它

2 个答案:

答案 0 :(得分:2)

可以使用 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)

styled 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]

styles 标签是根据 True 中的 conds 值应用的:

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

答案 1 :(得分:1)

您可以按照此处的建议进行操作:How to define color of specific cell in pandas dataframe based on integer position (e.g., 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 suggests 类似,只是它不使用 np.select,而是手动应用条件。