How to avoid few columns in a data frame while merging data with an other data frame?

Viewed 50

I have two data frames df1 and df2.

df1 =
A  B  C  D
1  2  3  7
.
. 

df2 = 
A  E  F  G
1  5  4  5
.
.

When I usually want to merge specific columns from two data frames using pandas I do this:

import pandas as pd

df3 = pd.merge(df1[[A,B]],df2[[A,G]], on='A', how='inner')

However, I am interested in knowing how to avoid a few columns in a data frame and merge the rest. For example, I want to avoid the columns Cand D in df1 and columns EandF in df2 while merging so the resultant df3 has only A,B,G columns only.

It is reverse engineering. When there are few columns in each data frame it may not be useful and the first method would be enough, but while working with hundreds of columns and if any few columns are to be avoided the second approach would be helpful.

2 Answers

How about drop:

df1.drop(['C','D'], axis=1).merge(df2.drop(['E','F'], axis=1), on='A')

try this:

df3=df1.merge(df2, on='A',how ="inner")
df3.drop(['E,'F',C','D'], axis=1)

this works but this solution is inefficient so dropping before merging will be optimal.

Related