2016-11-03 25 views
2

我成功合併了兩個數據框,但我也希望看到那些合併失敗的值。目的是驗證我作爲合併的結果擁有所有正確的值。是可以將它們轉儲到一個列表或更好的另一個數據框?是否可以列出未合併的數據框中的值?

在下面的代碼示例中; 'company_f'合併失敗,這是我需要看到的記錄。

import pandas as pd 

data1 = pd.DataFrame({'id': ['a12bcde0','b20bcde9'], 'title': ['company_a','company_b']}) 

data2 = pd.DataFrame({'serial_number': ['01a2b345','10ab2030','40ab4060'],'title':['company_a','company_b (123)','company_f']}) 

data2['title'].replace(regex=True,inplace=True,to_replace=r"\s\(.*\)",value=r'') 

pd.merge(data1, data2, on='title') 

回答

2

numpy的解決方案與numpy.setxor1d

print (np.setxor1d(data1.title,data2.title)) 
['company_f'] 

我認爲你可以使用外部聯接與參數indicator然後boolean indexing過濾:

df = pd.merge(data1, data2, on='title', how='outer', indicator=True) 

df1 = df[df._merge == 'both'] 
print (df1) 
     id  title serial_number _merge 
0 a12bcde0 company_a  01a2b345 both 
1 b20bcde9 company_b  10ab2030 both 

print (df1.drop('_merge', axis=1)) 
     id  title serial_number 
0 a12bcde0 company_a  01a2b345 
1 b20bcde9 company_b  10ab2030 

print (df[df._merge != 'both']) 
    id  title serial_number  _merge 
2 NaN company_f  40ab4060 right_only 

L = df.ix[df._merge != 'both', 'title'].tolist() 
print (L) 
['company_f'] 
+0

作品像一個魅力謝謝@jezrael – FunnyChef

相關問題