Antonio López Ruiz
Antonio López Ruiz

Reputation: 1466

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. i.e. Imagine you have a thousand columns.

Upvotes: 1

Views: 63

Answers (2)

BENY
BENY

Reputation: 323226

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

Upvotes: 3

rafaelc
rafaelc

Reputation: 59274

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

Upvotes: 2

Related Questions