突出显示选定的数据框行

时间:2020-05-04 15:53:19

标签: python pandas

我有一个数据框和两个列表,其中一个列表由颜色组成,另一个列表由目标组成。我想检查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>

1 个答案:

答案 0 :(得分:0)

如果要格式化整个行,则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)

输出:

enter image description here