我想知道是否有可能通过提供'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)
答案 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_on
和right_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