【问题标题】:How to merge two data frames having same column names horizontally on basis of similar values in one column如何根据一列中的相似值水平合并具有相同列名的两个数据框
【发布时间】:2022-12-21 13:42:22
【问题描述】:
我有两个数据框,如下所示:
| A |
B |
C |
D |
| Red |
36 |
1 |
type-1 |
| Blue |
78 |
2 |
type-1 |
| Green |
59 |
3 |
type-1 |
| A |
B |
C |
D |
| Orange |
78 |
5 |
type-2 |
| Purple |
59 |
7 |
type-2 |
| Brown |
36 |
9 |
type-2 |
我想在 B 列的基础上合并上面的两个数据框,合并后我想保留相同的列,如下所示:
| A |
B |
C |
D |
A |
B |
C |
D |
| Red |
36 |
1 |
type-1 |
Brown |
36 |
9 |
type-2 |
| Blue |
78 |
2 |
type-1 |
Orange |
78 |
5 |
type-2 |
| Green |
59 |
3 |
type-1 |
Purple |
59 |
7 |
type-2 |
是否可以使用 pandas 或任何其他 python 函数来执行此操作?
我试过使用 pd.merge 函数,但我需要更改列名。存在另一个名为 pd.concat 的函数,但我可以在其中提供列名称(“B”列)以进行合并吗?
非常感谢!
【问题讨论】:
标签:
python
python-3.x
pandas
dataframe
【解决方案1】:
您可以从两个 DataFrames 传递给参数 left_on 和 right_on 列,创建帮助列 key_0 也是如此,它在通过 DataFrame.merge 加入后被删除:
注意:Pandas 有重复列名的问题,这就是为什么 merge 用后缀 _x 和 _y 重命名它们的原因
df = df1.merge(df2, left_on=df1.B, right_on=df2.B).drop('key_0', axis=1)
print (df)
A_x B_x C_x D_x A_y B_y C_y D_y
0 Red 36 1 type-1 Brown 36 9 type-2
1 Blue 78 2 type-1 Orange 78 5 type-2
2 Green 59 3 type-1 Purple 59 7 type-2