简体   繁体   English

通过具有相同名称的列连接数据框

[英]Joining dataframes by the columns with same names

I have the following dataframes: 我有以下数据框:

df: df:

A      B      C
1      x      1
2      y      2

and

df2: df2:

A     C      D     E
3     3      x     l
4     4      z     k

I want the following: 我想要以下内容:

df_r: df_r:

A        C
1        1
2        2
3        3
4        4

Note: This is just and example, the answer should be capable of not knowing first hand what are the same columns. 注意:这仅是示例,答案应该能够不知道第一手什么是相同的列。 ie Imagine you have a thousand columns. 即想象一下您有一千列。

It is time to introduce concat with join 是时候介绍concatjoin

pd.concat([df1,df2],join='inner',ignore_index =True)
Out[30]: 
   A  C
0  1  1
1  2  2
2  3  3
3  4  4

Another way using align 使用align另一种方法

pd.concat(df1.align(df2,join='inner',axis=1),ignore_index =True)
Out[37]: 
   A  C
0  1  1
1  2  2
2  3  3
3  4  4

Both of the methods working for outer and inner join for merge index or columns 这两种方法都适用于合并indexcolumns outerinner columns

Simple with pd.concat pd.concat使用pd.concat

cols = set(df.columns).intersection(df2.columns)
pd.concat([df[cols], df2[cols]])

Also simple with df.append df.append也很简单

df[cols].append(df2[cols])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM