如何在pandas中连接两个具有不同列名的数据框?- Python [英] how to concat two data frames with different column names in pandas? - python

查看:82
本文介绍了如何在pandas中连接两个具有不同列名的数据框?- Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 将值放在 df2b 列中df1a 列.这是我试图实现的输出:

I'm trying to merge the two data frames using the keys from the df1. I think I should use pd.merge for this, but I how can I tell pandas to place the values in the b column of df2 in the a column of df1. This is the output I'm trying to achieve:

    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

推荐答案

只需使用 concatrename df2 的列,使其对齐:

Just use concat and rename the column for df2 so it aligns:

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 但你需要像上面一样重命名列:

similarly you can use merge but you'd need to rename the column as above:

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

这篇关于如何在pandas中连接两个具有不同列名的数据框?- Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆