代码之家  ›  专栏  ›  技术社区  ›  Phillip

基于列位置的Python合并

  •  0
  • Phillip  · 技术社区  · 6 年前

    ID employee        group
    1      Bob   Accounting
    2     Jake  Engineering
    3     Lisa  Engineering
    4      Sue           HR
    
    ID employee  hire_date
    1     Lisa       2004
    2      Bob       2008
    3     Jake       2012
    4      Sue       2014
    

    employee 列。唯一的问题是,不要提到列名 ,我只需要提到我将知道的雇员栏的位置。

    雇员

    import pandas as pd
    
    df1 = pd.DataFrame({'ID':[1,2,3,4], 'employee': ['Bob', 'Jake', 'Lisa', 'Sue'],
                        'group': ['Accounting', 'Engineering', 'Engineering', 'HR']})
    df2 = pd.DataFrame({'ID':[1,2,3,4],'employee': ['Lisa', 'Bob', 'Jake', 'Sue'],
                        'hire_date': [2004, 2008, 2012, 2014]})
    
    merged = pd.merge(df1, df2, left_on=df1.ix[:,[1]], right_on=df2.ix[:,[1]])
    

    但这是一个错误。有人能帮我吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Scott Boston    6 年前

    试试这个:

    df1.merge(df2, right_on=df2.columns[1], left_on=df1.columns[1])
    

    输出:

       ID_x employee        group  ID_y  hire_date
    0     1      Bob   Accounting     2       2008
    1     2     Jake  Engineering     3       2012
    2     3     Lisa  Engineering     1       2004
    3     4      Sue           HR     4       2014
    
        2
  •  1
  •   Alex Galarce    6 年前

    你可以用 list(df) 要访问可按位置引用的列名列表,请执行以下操作:

    merged = pd.merge(df1, df2, left_on = list(df1)[1], right_on = list(df2)[1])
    

    输出:

       ID_x employee        group  ID_y  hire_date
    0     1      Bob   Accounting     2       2008
    1     2     Jake  Engineering     3       2012
    2     3     Lisa  Engineering     1       2004
    3     4      Sue           HR     4       2014