python - 与 pandas 的一对多、左、外连接 (Python)

标签 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

预先感谢您的帮助。

最佳答案

您可以使用cumcount用于在 df2df3 中计数 ID2,以便按唯一进行合并。然后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

关于python - 与 pandas 的一对多、左、外连接 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46140609/

相关文章:

python - 通过 Numpy/Pandas 使用 (n x 1) 数据创建一个 n x m 多项式数组

regex - 如何连接行并添加分隔符?

python - 如何获取对象的名称?

python - 为什么我不能在 python curses 窗口中将 str() 添加到最后一行/最后一行?

python - 检测列名称并根据自定义函数创建新列

python - 检查 10 个不同集合之间的共同元素

MySQL查询多个表是从表多个项目?

MySQL JOIN 两张表(联合)

python - 给定外部订单,按日期时间月份的 Pandas 订单行

python - 如何将xls转换为xlsx