2017-09-13 55 views
2

我有兩個數據幀,我試圖合併。組合來自熊貓數據框的列的問題

   df1 
    code scale R1 R2... 
0 121  1  80 110 
1 121  2  NaN NaN 
2 121  3  NaN NaN 
3 313  1  60 60 
4 313  2  NaN NaN 
5 313  3  NaN NaN 
... 
      df2 
    code scale R1 R2... 
0 121  2  30 20 
3 313  2  15 10 
... 

我需要的基礎上,列codescale平等的值複製從df2df1

結果應該是這樣的:

   df1 
    code scale R1 R2... 
0 121  1  80 110 
1 121  2  30 20 
2 121  3  NaN NaN 
3 313  1  60 60 
4 313  2  15 10 
5 313  3  NaN NaN 
... 

的問題是,可以有很多列的像R1R2,我不能單獨檢查每一個,所以我想用的東西​​,但沒有任何結果給我。我做錯了什麼,但我不明白。我真的需要建議。

+2

如果兩個數據幀都具有R1/R2的值,您希望發生什麼?如果你想保留df1,你可以做'df1.set_index(['code','scale'])。fillna(df2.set_index(['code','scale']))。reset_index()' –

+0

@KenSyme why你不是回答嗎? – IanS

回答

4

要HAP做什麼如果兩個數據幀都具有R1/R2的值,那麼這個筆是筆嗎?如果你想保持DF1,你可以做

df1.set_index(['code', 'scale']).fillna(df2.set_index(['code', 'scale'])).reset_index() 

爲了保持DF2只是做fillna其他方式輪。以其他方式結合,請澄清問題!

+0

感謝您的回答!我忘記提及'df1'中的值,除了'scale'爲'1'的行以外總是空的。實際上,我想用'df2'和其他數據框填充數據。 –

3

試試這個嗎?

pd.concat([df,df1],axis=0).sort_values(['code','scale']).drop_duplicates(['code','scale'],keep='last')  
Out[21]: 
    code scale R1  R2 
0 121  1 80.0 110.0 
0 121  2 30.0 20.0 
2 121  3 NaN NaN 
3 313  1 60.0 60.0 
3 313  2 15.0 10.0 
5 313  3 NaN NaN 
3

對於combine_first這是一個很好的情況。它從傳遞的數據幀中替換調用數據幀中的空值。

df1.set_index(['code', 'scale']).combine_first(df2.set_index(['code', 'scale'])).reset_index() 

    code scale R1  R2 
0 121  1 80.0 110.0 
1 121  2 30.0 20.0 
2 121  3 NaN NaN 
3 313  1 60.0 60.0 
4 313  2 15.0 10.0 
5 313  3 NaN NaN 

其他解決方案

with fillna

df.set_index(['code', 'scale']).fillna(df1.set_index(['code', 'scale'])).reset_index() 

with add - 快一點

df.set_index(['code', 'scale']).add(df1.set_index(['code', 'scale']), fill_value=0)