2014-07-19 46 views
0
import pandas as pd 
from pandas import DataFrame 

l=[(1,10),(2,5), (3,7)] 
l2=[(1,5), (2,6), (3,8)] 
l3=[(2,3), (1,9), (3,9)] 

d1=DataFrame(l) 
d2=DataFrame(l2) 
d3=DataFrame(l3) 

j1=d1.join(d2, how='left') 

失敗,錯誤:異常:列重疊:Int64Index([0,1],D型細胞= int64類型)爲什麼我在使用python熊貓時未能加入兩個數據框?

什麼事?發生了什麼?

In [40]: d1 
Out[40]: 
    0 1 
0 1 10 
1 2 5 
2 3 7 

In [41]: d2 
Out[41]: 
    0 1 
0 1 5 
1 2 6 
2 3 8 

我需要的是加入d1和使用第一科拉姆D2,結果應該是,需要哪種類型的數據幀的操作?

0 1 2 
0 1 10 5 
1 2 5 6 
2 3 7 8 

回答

2

這是行不通的,它看起來你想要做的是添加只是你能達到使用concat最後一欄

In [15]: 
# just add the last column 
j1=pd.concat([d1,d2[[1]]],axis=1) 
j1 
Out[15]: 
    0 1 1 
0 1 10 5 
1 2 5 6 
2 3 7 8 

[3 rows x 3 columns] 

,或者你應該merge

In [19]:  
j1 = d1.merge(d2, how='left', on=[0]) 
j1 
Out[19]: 
    0 1_x 1_y 
0 1 10 5 
1 2 5 6 
2 3 7 8 

[3 rows x 3 columns] 

In [20]: 
# now rename the columns that clashed 
j1.rename(columns={'1_x':'1', '1_y':'2'}, inplace=True) 
j1 
Out[20]: 
    0 1 2 
0 1 10 5 
1 2 5 6 
2 3 7 8 

[3 rows x 3 columns] 

如果我們分析連接出了什麼問題,那麼除非您指定後綴,否則您會遇到無法解析的列衝突:

In [42]: 

j1=d1.join(d2, how='left',lsuffix='', rsuffix='_y') 
j1 
Out[42]: 
    0 1 0_y 1_y 
0 1 10 1 5 
1 2 5 2 6 
2 3 7 3 8 

[3 rows x 4 columns] 

我們現在可以刪除多餘的柱0_y並重命名添加的列:

In [43]: 

j1.drop(labels=['0_y'],axis=1,inplace=True) 
j1.rename(columns={'1_y':'2'},inplace=True) 
j1 
Out[43]: 
    0 1 2 
0 1 10 5 
1 2 5 6 
2 3 7 8 

[3 rows x 3 columns] 
+0

就是D2 [[1]]和d2之間的差[1],這是相同的爲d2。得到(1)? – crazyminer

+1

第一個返回一個數據幀,第二個數據幀 – EdChum