简体   繁体   中英

Joining dataframes by the columns with same names

I have the following dataframes:

df:

A      B      C
1      x      1
2      y      2

and

df2:

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

I want the following:

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

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

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

Simple with pd.concat

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

Also simple with df.append

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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