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