簡體   English   中英

Pandas - 在另一列中具有相同值的行中的一列中查找重復條目

[英]Pandas - Find duplicated entries in one column within rows with equal values in another column

假設數據幀df如下所示:

  col1 col2
0    a    A
1    b    A
2    c    A
3    c    B
4    a    B
5    b    B
6    a    C
7    a    C
8    c    C

我想找到的那些值col2那里有重復的條目acol1 在這個例子中,結果應該是['C]' ,因為對於df['col2'] == 'C'col1有兩個a作為條目。

我試過這種方法

df[(df['col1'] == 'a') & (df['col2'].duplicated())]['col2'].to_list()

但這只有在由col2定義的行塊中的a位於塊的開頭或結尾時才有效,具體取決於您如何定義duplicated()keep關鍵字。 在這個例子中,它返回['B', 'C'] ,這不是我想要的。

僅對過濾的行使用Series.duplicated

df1 = df[df['col1'] == 'a']

out = df1.loc[df1['col2'].duplicated(keep=False), 'col2'].unique().tolist()
print (out)
['C']

另一個想法是使用DataFrame.duplicated列和鏈 w 只匹配a

out = df.loc[df.duplicated(subset=['col1', 'col2'], keep=False) & 
             (df['col1'] == 'a'), 'col2'].unique().tolist()
print (out)
['C']

使用Groupby.countindex.get_level_values更通用的解決方案:

In [2632]: x = df.groupby(['col1', 'col2']).col2.count().to_frame()
In [2642]: res = x[x.col2 > 1].index.get_level_values(1).tolist()

In [2643]: res
Out[2643]: ['C']

您可以按col2col1進行分組並計算'a'出現次數

>>> s = df.col1.groupby(df.col2).sum().str.count('a').gt(1)
>>> s[s].index.values
array(['C'], dtype=object)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM