如何在熊猫中连接两个具有不同列名的数据框?- Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36925354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:33:28  来源:igfitidea点击:

how to concat two data frames with different column names in pandas? - python

pythonpandasmerge

提问by HappyPy

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]})

I'm trying to merge the two data frames using the keys from the df1. I think I should use pd.mergefor this, but I how can I tell pandas to place the values in the bcolumn of df2in the acolumn of df1. This is the output I'm trying to achieve:

我正在尝试使用df1. 我想我应该用pd.merge这一点,但我我怎么能告诉大熊猫放置值的bdf2adf1。这是我试图实现的输出:

    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

回答by EdChum

Just use concatand renamethe column for df2so it aligns:

只需使用concatrename列,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

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

同样,您可以使用,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

回答by scottlittle

Use numpy to concatenate the dataframes, so you don't have to rename all of the columns (or explicitly ignore indexes). np.concatenatealso works on an arbitrary number of dataframes.

使用 numpy 连接数据帧,因此您不必重命名所有列(或显式忽略索引)。 np.concatenate也适用于任意数量的数据帧。

df = pd.DataFrame( np.concatenate( (df1.values, df2.values), axis=0 ) )
df.columns = [ 'a', 'x', 'y' ]
df