2014-07-19 45 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