使用pandas进行一对多,左外连接(Python)

时间:2017-09-10 12:16:33

标签: python pandas join outer-join

我尝试使用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

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以在ID2df2中使用cumcount来计算df3,以便通过唯一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
相关问题