2017-04-14 53 views
2

我在問一個類似於this one的問題,但我需要的東西有點不同。我有兩個pandas.DataFrames,我需要合併它們。如何結合兩個pandas.DataFrames列表作爲列?

這裏是第一df_1

id  attr   fruit_list 
--------------------------------------- 
0  42   [orange, apple] 
1  57   [lemon] 
2  86   [kiwi] 
3  33   [pineapple, pear] 
4  11   [apple, lemon] 

,這裏是第二df_2

id  fruit_list 
-------------------------------------- 
0  [fruit1,] 
1  [fruit4, fruit2] 
2  [fruit2, fruit8] 
3  [fruit3,] 
4  [fruit3,] 

我需要合併這兩個DataFrames得到的輸出是這樣的:

id  attr   fruit_list 
--------------------------------------------- 
0  42   [orange, apple, fruit1] 
1  57   [lemon, fruit4, fruit2] 
2  86   [kiwi, fruit2, fruit8] 
3  33   [pineapple, pear, fruit3] 
4  11   [apple, lemon, fruit3] 

如何我可以做到這一點嗎?我曾看過documentation,但我無法想出辦法。

回答

3

如果ID,以便匹配,你可以添加兩列:

df1.fruit_list = df1.fruit_list + df2.fruit_list 
df1 

enter image description here

或者,如果需要就id列合併,您可以合併,然後添加fruit_list列:

(df1.merge(df2, on = "id") 
.assign(fruit_list = lambda x: x.fruit_list_x + x.fruit_list_y) 
.drop(["fruit_list_x", "fruit_list_y"], 1)) 

enter image description here