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

问题描述 投票:2回答:1

我有一个带有A和B两列的dataFrame。我必须使用熊猫来删除dataFrames的子集,以删除所有重复的值。

For Example

我的dataFrame看起来像这样

**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

我该怎么做?

提前感谢。

python pandas dataframe duplicates conditional-formatting
1个回答
2
投票

您可以使用此:

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'])

示例工作代码:

enter image description here

说明:首先,我们将数据帧stack放入系列中,然后用stack查找duplicated以将所有重复项标记为true:

duplicated

在此之后,我们keep=False该数据帧给出了具有相同数据帧结构的布尔数据帧:

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

一旦有了这个,我们就将背景色分配给值,如果为True,则使用unstack()为无色>

© www.soinside.com 2019 - 2024. All rights reserved.