在两列之间查找唯一值

时间:2020-03-22 19:23:41

标签: python pandas dataframe duplicates

我一直在研究各种问题,但是没有找到适合这种情况的问题。

我有两列包含电子邮件。第一列(CollectedE)包含32000,第二列(UndE)包含14987。

我需要在第二列中找到所有电子邮件(第一列中不存在),然后将它们输出到全新的列中。

我已经尝试过类似的方法,但是由于列中的两个长度不同,所以无法使用。

import pandas as pd
import numpy as np
df = pd.read_csv('data.csv', delimiter=";")

df['is_dup'] = df[['CollectedE', 'UndE']].duplicated()
df['dups'] = df.groupby(['CollectedE', 'UndE']).is_dup.transform(np.sum)
# df outputs:
df['is_dup'] =[![enter image description here][1]][1] df[['CollectedE', 'UndE']].duplicated()
df['dups'] = df.groupby(['CollectedE', 'UndE'])

df

这是两列的图片,如果有帮助的话。但是似乎所有其他情况都与删除一列中的重复项,删除具有相同值的行,查找频率或类似情况有关。

enter image description here

但我希望您能提供帮助。谢谢!

4 个答案:

答案 0 :(得分:1)

也许pandas.Index.difference可以为您提供帮助。

答案 1 :(得分:1)

您可以使用isin来简化操作,而使用~来反转操作。

df = pd.DataFrame({'CollectedE' : ['abc@gmail.com','random@google.com'],
             'UndE' : ['abc@gmail.com','unique@googlemail.com']})

df['new_col'] = df[~df['CollectedE'].isin(df['UndE'])]['UndE']

print(df)
          CollectedE                   UndE                new_col
0      abc@gmail.com          abc@gmail.com                    NaN
1  random@google.com  unique@googlemail.com  unique@googlemail.com

答案 2 :(得分:1)

这是一个使用索引差异方法和合并的工作示例。

df = pd.DataFrame({'column_a':['cat','dog','bird','fish','zebra','snake'],
               'column_b':['leopard','snake','bird','sloth','elephant','dolphin']})

idx1 = pd.Index(df['column_a'])
idx2 = pd.Index(df['column_b'])

x = pd.Series(idx2.difference(idx1), name='non_matching_values')

df.merge(x, how='left', left_on='column_b', right_on=x.values)

column_a    column_b    non_matching_values
0   cat leopard leopard
1   dog snake   NaN
2   bird    bird    NaN
3   fish    sloth   sloth
4   zebra   elephant    elephant
5   snake   dolphin dolphin

答案 3 :(得分:1)

这是我已经实现的东西。我已经利用了右外部连接并在列表中转换了输出列,并将其附加在源数据帧中。

#Creating dataframe
df = pd.DataFrame({'col1': ['x', 'y', 'z', 'x1'], 'col2': ['x', 'x2', 'y', np.nan]})

#Applying right join and keeping values which are present in 2nd column only
df2 = pd.merge(df[['col1']], df[['col2']], how = 'outer', left_on = ['col1'], right_on 
= ['col2'], indicator = True)

df2 = df2[df2['_merge'] == 'right_only'][['col2']]

为保持相同长度的数据帧,添加了空值。

#Creating list and adding it as column in source dataframe
df2_list = df2.append(pd.DataFrame({'col2': [np.nan for x in range(len(df) - 
len(df2))]}))['col2'].to_list()

df['col3'] = df2_list

输出:

df
    col1 col2 col3
0    x    x   x2
1    y   x2  NaN
2    z    y  NaN
3   x1  NaN  NaN

您也可以在列表之前转换列,并使用空值扩展列表。

相关问题