[英]Find unique values between two columns
我一直在經歷各種問題,但還沒有找到適合這種情況的問題。
我有兩列電子郵件。 第一列 (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
這是兩列的圖片,如果有幫助的話。 但似乎所有其他情況都是關於刪除一列中的重復項、刪除具有相同值的行、查找頻率或類似的。
但我希望你能幫忙。 謝謝!
也許pandas.Index.difference
可以幫助你。
您可以使用很簡單的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
這是一個使用索引差異方法和合並的工作示例。
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
這是我實現的東西。 我在列表中使用了右外連接和轉換的輸出列,並將其附加到源數據框中。
#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
您也可以之前轉換列表列並使用空值擴展列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.