一对多,左,外接Pandas(Python)

2024-06-11 21:56:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我使用的代码如下:

^{pr2}$

代码将表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

提前谢谢你的帮助。在


Tags: iotestidtablesseekdsb
1条回答
网友
1楼 · 发布于 2024-06-11 21:56:13

您可以在df2和{}中使用^{}表示计数ID2,并使用{}进行唯一合并pairs。然后是^{}和聚合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

相关问题 更多 >