2015-11-06 44 views
0

我知道this的問題,我一直在努力完成它。我有兩個dataframes df1df2看起來像:熊貓 - 檢查數據框中的變化

DF1

U,T,L,P 
01,string1,a,0.9 
02,string2,b,0.9 
03,string3,c,0.9 

DF2

U,T,L,P 
01,string1,a,0.9 
02,string2,d,0.9 
03,string3,c,0.9 

基本上是唯一的區別是在L列和第二行,其中b變爲d。我想查看比較數據框的差異,保留所有現有的信息。按照上面的問題,我嘗試到目前爲止已:

difference_locations = np.where(df1 != df2) 

changed_from = df1.values[difference_locations] 

changed_to = df2.values[difference_locations] 

a = pd.DataFrame({'from': changed_from, 'to': changed_to}) 

返回:

from to 
0 b d 

結果是正常的,但我想也添加有關初始數據集的其餘信息。發生在列LP唯一的變化,從而使結果我要強調的變化:

U T  from to 
0 02 string2 b d 

我試圖建立數據框的東西,如將現有的列:

a = pd.DataFrame({'U': df1['U'],'from': changed_from, 'to': changed_to}) 

但它當然不起作用,因爲我應該在索引上執行查找,以獲得對應於更改的行的UT的正確值。

回答

1

您可以在列L上使用函數merge。然後這一列重命名爲to

a = pd.DataFrame({'from': changed_from, 'L': changed_to}) 
print a 
# L from 
#0 d b 

out = pd.merge(a, df2, on=['L']) 
out.rename(columns={'L':'to'}, inplace=True) 
out = out[['U','T','from', 'to']] 
print out 
# U  T from to 
#0 2 string2 b d