按索引突出显示(彩色) pandas 数据框 [英] highlight (color) a panda data frame row by index

查看:66
本文介绍了按索引突出显示(彩色) pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据帧df1:

i have two data frame df1:

d1 = {"col1" : ['A', 'B', 'C'],
      "Col2": ["home", "car","banana" ]}

d2 = {"col1" : ['D', 'F','C'],
      "Col2": ["garden", "boat","banana" ]}

df1 = pd.DataFrame(data=d1)
df2 = pd.DataFrame(data=d2)

new_df = pd.merge(df1, df2,  on ='col1', how='outer')
new_df

所以我想做的是突出显示在两个数据框中找到的第三行香蕉。
我正在使用样式文档来找到解决方案但没有运气。
我只能突出显示一行,但是当我有多行时它不起作用。
请伸出援助之手

So what I am trying to do is highlight the third row "banana" that was found in the two data frames. I was using the Styling documentation to find a solution but no luck. I was able to highlight only a single row, but when I have multiple rows it doesn't work. Please give a helping hand

推荐答案

如果要突出显示两行(例如索引2和4),是 answer

In case you want to highlight two rows (say index 2 and 4) it is a almost a duplicate of this answer

new_df.style.apply(lambda x: ['background: lightgreen' if x.name in [2,4] 
                              else '' for i in x], 
                   axis=1)

如果相反,您希望突出显示列表中包含给定名称的每一行(即 lst = ['car','boat'] )您可以使用

If instead you are looking to highlight every row that contain a given name in a list (i.e. lst = ['car', 'boat']) you can use

new_df.style.apply(lambda x: ['background: lightgreen' if (set(lst).intersection(x.values)) 
                              else '' for i in x], 
                   axis=1)

这篇关于按索引突出显示(彩色) pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆