2016-10-26 81 views
2

我需要查找給定熊貓數據框中列值不同的位置。比較熊貓數據框中的列值

我使用技術組裝我的數據幀在這裏描述:compare two pandas data frame

使用此代碼,我可以得到添加的行和新舊數據集之間刪除的行。其中df1是舊數據集,df2是新數據集。他們有相同的模式。

m = df1.merge(df2, on=['ID', 'Name'], how='outer', suffixes=['', '_']) 
adds = m.loc[m.GPA_.notnull() & m.GPA.isnull()] 
deletes = m.loc[m.GPA_.isnull() & m.GPA.notnull()] 

我想要做的是過濾掉從合併數據框中的添加和刪除則列值進行比較是這樣的:

for col in m.columns: 
    m["diff_%s" % field] = m[field] != m["%s_" % field] 

這應導致補充說,檢查值的多個布爾列變化。所以我的問題是,如何在應用此列邏輯之前過濾出添加和刪除行?

附加信息:

_data_orig = [ 
[1, "Bob", 3.0], 
[2, "Sam", 2.0], 
[3, "Jane", 4.0]] 
_columns = ["ID", "Name", "GPA"] 

_data_new = [ 
     [1, "Bob", 3.2], 
     [3, "Jane", 3.9], 
     [4, "John", 1.2], 
     [5, "Lisa", 2.2] 
    ] 
_columns = ["ID", "Name", "GPA"] 

df1 = pd.DataFrame(data=_data_orig, columns=_columns) 
df2 = pd.DataFrame(data=_data_new, columns=_columns) 

m = df1.merge(df2, on=['ID', 'Name'], how='outer', suffixes=['', '_']) 
adds = m.loc[m.GPA_.notnull() & m.GPA.isnull()] 
deletes = m.loc[m.GPA_.isnull() & m.GPA.notnull()] 

# TODO: add code to remove adds/deletes here 
# array should now be: [[1, "Bob", 3.2], 
#  [3, "Jane", 3.9]] 
for col in m.columns: 
    m["diff_%s" % field] = m[field] != m["%s_" % field] 
# results in: 
# array with columns ['ID', 'Name', 'GPA', 'Name_', 'GPA_','diff_GPD', 'diff_Name' 
# ... DO other stuff 
# write to csv 
+0

才能添加您樣本數據的期望輸出? – jezrael

+0

@jezrael肯定,現在更新。 –

+0

@jezrael代碼根據要求更新 –

回答

3

可以使用Index.union爲concanecate都indexes然後drop行與idx

idx = adds.index.union(deletes.index) 
print (idx) 
Int64Index([1, 3, 4], dtype='int64') 

print (m.drop(idx)) 
    ID Name GPA GPA_ 
0 1 Bob 3.0 3.2 
2 3 Jane 4.0 3.9 

boolean indexing另一種解決方案:

mask = ~((m.GPA_.notnull() & m.GPA.isnull()) | (m.GPA_.isnull() & m.GPA.notnull())) 
print (mask) 
0  True 
1 False 
2  True 
3 False 
4 False 
dtype: bool 

print (m[mask]) 
    ID Name GPA GPA_ 
0 1 Bob 3.0 3.2 
2 3 Jane 4.0 3.9