2017-04-07 75 views
1

我有兩個不同長度的熊貓數據框,當兩列匹配時,我需要有條件地覆蓋從一個到另一個的值。有條件地加入多個索引的熊貓DF

df1.val = df2.val where df1.val == null and df1.key1 == df2.key1 and df1.key2 == df2.key2 

df1df2具有非常不同的組列和行的長度,保存爲key1key2val。唯一可以保證的是,df1中的每(key1, key2)df2中只有一個(key1, key2)

到目前爲止,我一直走下去的

df1.loc[df1.val.isnull(), "val"] = df2.val 

嘗試設置指標相匹配的路徑,但我還沒有在任何地方得到。

我知道這裏有一些加入項目,但是我還沒有在這方面取得任何進展。一些語法幫助將不勝感激。

編輯數據:

DF1:

First Last Val Random1 ... 
John Smith 4 x 
Todd Smith 5 Nan 
John Todd Nan z 

DF2:

First Last Val Random2 ... 
John Smith 7 4 
Todd Smith 6 9 
John Todd  3 3 
Eric Smith 5 2 

結果:

First Last Val Random1 ...OtherDF1Cols... 
John Smith 4 x 
Todd Smith 5 Nan 
John Todd  3 z 
+2

你可以添加一些數據樣本的選擇嗎? – jezrael

回答

1

設定指數的第一,然後fillna

DF1.set_index(['First', 'Last']).fillna(DF2.set_index(['First', 'Last'])) 

      Val 
First Last  
John Smith 4.0 
Todd Smith 5.0 
John Todd 3.0 

使用combine_first包括來自dataframes

DF1.set_index(['First', 'Last']).combine_first(DF2.set_index(['First', 'Last'])) 

      Val 
First Last  
Eric Smith 5.0 
John Smith 4.0 
     Todd 3.0 
Todd Smith 5.0 

或者,只更新Val柱,並將其限制爲只有一排排所有的東西第一個

d1 = DF1.set_index(['First', 'Last']) 
d2 = DF2.set_index(['First', 'Last']) 
print(d1.combine_first(d2[['Val']]).loc[d1.index].reset_index()) 

    First Last Val 
0 John Smith 4.0 
1 Todd Smith 5.0 
2 John Todd 3.0 

使用update

d1 = DF1.set_index(['First', 'Last']) 
d2 = DF2.set_index(['First', 'Last']) 
d1.update(d2.Val, overwrite=False) 
d1.reset_index() 

    First Last Val 
0 John Smith 4.0 
1 Todd Smith 5.0 
2 John Todd 3.0 
+0

我不想填充所有空值,只是val列中的值。 –

+0

@SeanKramer在那裏應該可以工作 – piRSquared

+0

如果你想要替換null和0值,你會如何處理它? –