How to merge in python based on a condition?
I would like to know if there is a way to merge two dataframes using an if statement. for example
DF
number account_name classification
1 name named
2 place partner
3 animal class
4 thing territory
5 dog home
df1
account_name Number country
name 1 xx
place 2 xy
animal 7 yz
dog 8 zx
I am looking for the code as below
pd.merge(df,df1, on= 'account_name') if df[number] == df1[number]
the result should be like
number account_name classification number Country
1 name named 1 xx
2 place partner 2 xy
I tried a lambda function, the code was
x['nn'] = x.apply(lambda y: pd.merge(df, df1, on = 'account_name') if df[number] == df1[number] else 1, axis=1)
+3
source to share
1 answer
It seems you need to add a column to the parameter on
:
df = pd.merge(df,df1, on= ['account_name', 'number'])
print (df)
number account_name classification country
0 1 name named xx
1 2 place partner xy
But if the column names are different, use the parameters left_on
and right_on
in merge
:
df = pd.merge(df,
df1,
left_on= ['account_name', 'number'],
right_on= ['account_name', 'Number'])
print (df)
number account_name classification Number country
0 1 name named 1 xx
1 2 place partner 2 xy
+4
source to share