【问题标题】:why i failed to join two dataframes when using python pandas?为什么我在使用 python pandas 时未能加入两个数据框?
【发布时间】:2014-09-10 18:08:00
【问题描述】:
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], dtype=int64)

怎么了?发生了什么?

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,结果应该是,需要哪种DataFrame操作?

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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这行不通,看起来您想要做的只是添加您可以使用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]
    

    【讨论】:

    • d2[[1]] 和 d2[1] 和 d2.get(1) 有什么区别?
    • 第一个返回一个数据框,第二个返回一个系列
    猜你喜欢
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多