df1 = pd.DataFrame({'a':[1,2,3],'x':[4,5,6],'y':[7,8,9]})
df2 = pd.DataFrame({'b':[10,11,12],'x':[13,14,15],'y':[16,17,18]})
我正在尝试使用 df1
中的键合并两个数据帧。我想我应该为此使用 pd.merge
,但我如何告诉 pandas 将值放在 df2
的 b
列中df1
的 a
列。这是我要实现的输出:
a x y
0 1 4 7
1 2 5 8
2 3 6 9
3 10 13 16
4 11 14 17
5 12 15 18
最佳答案
只需使用 concat
和 rename
df2
的列,因此它对齐:
In [92]:
pd.concat([df1,df2.rename(columns={'b':'a'})], ignore_index=True)
Out[92]:
a x y
0 1 4 7
1 2 5 8
2 3 6 9
3 10 13 16
4 11 14 17
5 12 15 18
类似地,您可以使用merge
,但您需要像上面那样重命名该列:
In [103]:
df1.merge(df2.rename(columns={'b':'a'}),how='outer')
Out[103]:
a x y
0 1 4 7
1 2 5 8
2 3 6 9
3 10 13 16
4 11 14 17
5 12 15 18
关于python - 如何在 Pandas 中连接两个具有不同列名的数据框? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36925354/