【问题标题】:One to many, left, outer join with pandas (Python)一对多,左,外连接与熊猫(Python)
【发布时间】:2018-02-18 19:18:34
【问题描述】:

我正在尝试使用 Python 2.7 和 pandas 将三个表连接在一起。我的表格如下所示:

Table 1
ID  |  test
1   |  ss
2   |  sb
3   |  sc

Table 2
ID  |  tested  |  value1  |  Value2  |  ID2
1   |  a       |  e       |  o       |  1
1   |  axe     |  ee      |  e       |  1
1   |  bce     |  io      |  p       |  3
2   |  bee     |  kd      |  …       |  2
2   |  bdd     |  a       |  fff     |  3
3   |  db      |  f       |  yiueie  |  2

Table 3
ID2  |  type
1    |  i
1    |  d
1    |  h
3    |  e
1    |  o
2    |  ou
2    |  oui
3    |  op

我使用的代码如下:

import pandas as pd

xl = pd.ExcelFile(r'C:\Users\Joe\Desktop\Project1\xlFiles\test1.xlsx')
xl.sheet_names
df = xl.parse("Sheet1")
df.head()

xl2 = pd.ExcelFile(r'C:\Users\Joe\Desktop\Project1\xlFiles\test2.xlsx')
xl2.sheet_names
df2 = xl2.parse("Sheet1")
df2.head()

xl3 = pd.ExcelFile(r'C:\Users\Joe\Desktop\Project1\xlFiles\test3.xlsx')
xl3.sheet_names
df3 = xl3.parse("Sheet1")
df3.head()

df3 = df3.groupby('ID2')['type'].apply(','.join).reset_index()

s1 = pd.merge(df2, df3, how='left', on=['ID2'])

代码按照我的意愿将表 3 连接到表 2。但是,我不知道如何将多列分组以将 s1 加入表 1。我需要将 s1 中每一列的信息添加到表 1,但我只想要每个 ID 值一行(总共 3 行)。有谁知道我会怎么做?

我的预期输出,供参考,如下:

ID  |  test  |  type     |  tested     |  value1   |  ID2  
1   |  ss    |  i,d,h,o  |  a,axe,bce  |  e,ee,io  |  1,1,3
2   |  sb    |  ou,oui   |  bee,bdd    |  kd,a     |  2,3
3   |  sc    |  e,op     |  db         |  f        |  2

提前感谢您的帮助。

【问题讨论】:

    标签: python pandas join outer-join


    【解决方案1】:

    您可以在df2df3 中使用cumcount 计数ID2 以通过唯一pairs 合并。然后groupby 和聚合join

    最后使用join

    df2['g'] = df2.groupby('ID2').cumcount()
    df3['g'] = df3.groupby('ID2').cumcount()
    df23 = pd.merge(df2, df3, how='left', on=['g','ID2']).astype(str).groupby('ID').agg(','.join)
    #for same dtype for match - int
    df23.index = df23.index.astype(int)
    print (df23)
           tested   value1   Value2    ID2      g   type
    ID                                                  
    1   a,axe,bce  e,ee,io    o,e,p  1,1,3  0,1,0  i,d,e
    2     bee,bdd     kd,a  ...,fff    2,3    0,1  ou,op
    3          db        f   yiueie      2      1    oui
    
    df = df1.join(df23, on='ID')
    #subset and desired order of output columns
    cols = ['ID','test','type','tested','value1','ID2']
    df = df[cols]
    print (df)
       ID test   type     tested   value1    ID2
    0   1   ss  i,d,e  a,axe,bce  e,ee,io  1,1,3
    1   2   sb  ou,op    bee,bdd     kd,a    2,3
    2   3  sci    oui         db        f      2
    

    【讨论】:

    • 嘿,jezrael - 这正是我想要的。你真的很棒。非常感谢您的快速回复!
    猜你喜欢
    • 2018-07-11
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2018-11-05
    • 2017-08-26
    • 2017-10-15
    相关资源
    最近更新 更多