mercredi 22 mars 2017

How to merge in python based on condition?

I would like to know if there is a possible way to merge two dataframes by giving 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 a code like below

pd.merge(df,df1, on= 'account_name') if df[number] == df1[number]

the result sould be like

number  account_name  classification  number Country
     1        name         named          1      xx
     2        place        partner        2      xy

I tried the lambda function as well, code was

x['nn'] = x.apply(lambda y: pd.merge(df, df1, on = 'account_name')  if df[number] == df1[number] else 1, axis=1)

Aucun commentaire:

Enregistrer un commentaire