如何基于条件在python中合并?

时间:2017-03-22 13:21:48

标签: python pandas if-statement merge

我想知道是否有可能通过提供'if'语句来合并两个数据帧。 例如

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

我正在寻找下面的代码

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

结果应该像

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

我也试过了lambda函数,代码是

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

1 个答案:

答案 0 :(得分:4)

您似乎需要在参数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

但如果列名不同,请在merge中使用参数left_onright_on

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