2016-03-01 64 views
2

我想連接熊貓(python) 中的兩個數據幀(df1,df2),使得結果將包含df1的所有索引(唯一和共同),無論df2具有但不是那裏在df1。舉個例子:不能連接兩個數據幀

DF1

 
    col1 col2 
0  1 2 
1  2 3 
2  3 4 

DF2

 
    col1 col2 
1  4 6 
2  2 3 
3  5 5 

我想要的結果是這樣的:

 
    col1 col2 
0  1 2 
1  2 3 
2  3 4 
3  5 5 
+0

我不繼。 – bernie

+0

那麼,真正的問題是什麼? –

回答

5

使用combine_first

df3 = df1.combine_first(df2) 

print(df3) 

產生

col1 col2 
0  1  2 
1  2  3 
2  3  4 
3  5  5 
0

定義要行的列表從df2得到一個ð它們串聯到df1

ids = [x for x in df2.index if x not in df1.index] 
pd.concat([df1, df2.ix[ids]])