使用 pandas 对重复值进行条件格式化

Conditional Formatting on duplicate values using pandas

我有一个包含 2 列 A 和 B 的数据帧。我必须使用 pandas 分离出数据帧的子集以删除所有重复值。

For Example

我的数据框看起来像这样

**A     B**
1     1
2     3
4     4
8     8 
5     6
4     7

那么输出应该是

**A     B**
1     1       <--- both values Highlighted
2     3
4     4       <--- both values Highlighted
8     8       <--- both values Highlighted 
5     6
4     7       <--- value in column A highlighted

我该怎么做?

提前致谢。

你可以使用这个:

def color_dupes(x):
    c1='background-color:red'
    c2=''
    cond=x.stack().duplicated(keep=False).unstack()
    df1 = pd.DataFrame(np.where(cond,c1,c2),columns=x.columns,index=x.index)
    return df1
df.style.apply(color_dupes,axis=None)
# if df has many columns: df.style.apply(color_dupes,axis=None,subset=['A','B'])

示例工作代码:

说明: 首先我们 stack the dataframe so as to bring all the columns into a series and find duplicatedkeep=False 将所有重复标记为 true:

df.stack().duplicated(keep=False)

0  A     True
   B     True
1  A    False
   B    False
2  A     True
   B     True
3  A     True
   B     True
4  A    False
   B    False
5  A     True
   B    False
dtype: bool

在此之后我们 unstack() 数据帧给出了一个具有相同数据帧结构的布尔数据帧:

df.stack().duplicated(keep=False).unstack()
       A      B
0   True   True
1  False  False
2   True   True
3   True   True
4  False  False
5   True  False

一旦我们有了这个,我们将背景颜色分配给值,如果为真,否则没有颜色使用 np.where