python - 突出显示选定的数据框行
问题描述
我有一个数据框和两个列表,其中一个列表由颜色组成,另一个由目标组成。我想检查 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>
解决方案
如果要格式化整行,那么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)
输出:
推荐阅读
- pytorch - 线性层输入大小 Pytorch
- c# - .net 核心中是否有任何公共 MemberNotNull/MemberNotNullWhen 属性
- java - UserDetailsService 用户名是否必须与合同中的 UserDetails 用户名相同?
- java - 如何在分页和使用 order by 时列出 Google Drive API v3 上的所有根文件夹和共享?
- javascript - 我的局部变量没有更新全局变量?
- python - 为什么我的网页抓取结果在循环浏览每个网页后不会打印?
- javascript - node.js 发布方法 req.body 未定义,即使使用 body-parser
- javascript - 如何使用 JavaScript 获取操作系统名称和版本?
- flutter - Flutter 在 Column 内使用 TabBar 而不是 AppBar
- mongodb - 查询元素,如果它们的对象数组具有重复元素的属性