特定多索引列的条件格式

问题描述 投票:0回答:1

如何应用条件格式(如果值> 1,则以黄色突出显示。),不是在整个表格上,而是仅在这两列上:

  • “比较结果.NoMatch”
  • “假”

我只能适用于整个表。

我有这个代码:

styled_df = result.loc[:,idx[:,'ComparisonResult.NoMatch']]
                  .style.apply(lambda x : ['font-weight: bold; background-color: yellow' 
                                          if value >= 1 else '' for value in x])

但这基本上只留下了 ComparisonResult.NoMatch Column 作为我的结果。

顺便说一句,我正在使用 Visual Studio Code,但我没有看到非常丰富的 IntelliSense,例如在“值”字段上按点没有任何提示。我的扩展安装有问题吗?

python pandas dataframe visual-studio-code multi-index
1个回答
0
投票

您建议的代码存在问题:

  • 事实上,要格式化的数据框上的
    .loc
    只会限制您的视图,而不会选择要应用格式的区域。
  • idx
    的起源和目的尚不清楚。

这就是您所需要的:

使用

subset
参数到
apply
,如

中建议的
df.style.apply(lambda x: ['font-weight: bold; background-color: yellow' if value >= 1 else '' for value in x], 
               subset=[ ('Match','comparisonResult.NoMatch'), ('Match','False') ])

(似乎

result
可能是格式化之前的多索引数据框的名称,但我不确定。我称之为
df
。)

顺便说一下,为了更容易重用,您可以像这样整理:

Import numpy as np

def highlighter(x):
    return np.where(x>=1, 'font-weight: bold; background-color: yellow', None)

df.style.apply(highlighter, 
               subset=[ ('Match','comparisonResult.NoMatch'),
                        ('Match','False') ])
© www.soinside.com 2019 - 2024. All rights reserved.