![](/img/trans.png)
[英]Select rows with equal values in one column and different values in another column Pandas Python
[英]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
那里有重復的條目a
在col1
。 在這個例子中,結果應該是['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.count
和index.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']
您可以按col2
對col1
進行分組並計算'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.