首页 > 解决方案 > 突出显示选定的数据框行

问题描述

我有一个数据框和两个列表,其中一个列表由颜色组成,另一个由目标组成。我想检查 C 列中的数据是否在目标中,如果是,我希望整行突出显示。

我写了下面的代码

colour = ["red","blue","yellow"]
targets = ["talk","cry","laugh"]

view = pd.DataFrame({
         'B':[1,2,3,4,5],
         'C':["love","laff","laugh","talk","talk"]
       })


def higlight_Cell(x):
    count=0
    for column in view:
        for i in targets:
            if i in view[column]:
                return ['background-color: {}'.format(color[i])]
                count+=1

view.style.apply(higlight_Cell, axis=0)

运行代码时,我收到以下错误:

ValueError: Function <function higlight_Cell at 0x000001E16AF0B168> returned the wrong shape.
Result has shape: (2,)
Expected shape:   (5, 2)
Out[41]: <pandas.io.formats.style.Styler at 0x1e16d587508>

标签: pythonpandas

解决方案


如果要格式化整行,那么x就是一行,所以要访问C索引。此外,由于x是一行,因此您希望返回一个长度相同的格式数组x(这是错误所抱怨的)

def highlight(x):
    for c,t in zip(colour, targets):
        # check for 'C' value
        if x.loc['C']==t: 
            return [f'background-color: {c}']*len(x)

        # if you want to check for any value, replace the above with
        # if x.eq(t).any(): return [f'background-color: {c}']*len(x)

    return ['']*len(x)

view.style.apply(highlight, axis=1)

输出:

在此处输入图像描述


推荐阅读