如何用多个条件进行左联接?

时间:2019-05-21 07:42:29

标签: pandas python-2.7

我试图像这样的SQL请求在两个数据帧上使用Python Pandas进行左连接:

SELECT df1.Name, df2.CP

FROMdf1

LEFT JOIN df2 ON (df1.City1 = df2.City) OR (df1.City2 = df2.City) OR (df1.City3 = df2.City)

你能帮我做到吗?

例如,我有2个数据框:

df1 = pd.DataFrame({'Name':['toto', 'titi', 'tutu'], 'City1':['NY', 'Chic', 'Paris'], 'City2':['N-Y', 'Chicago', 'Paries'], 'City3':['New-York', 'chicagooo', 'Pari']}) 
df2 = pd.DataFrame({'City':['New-York', 'Chicago', 'Paris'], 'CP':['1', '2', '3']})

预期结果是这样的:

Name    CP
toto    1
titi    2
tutu    3

1 个答案:

答案 0 :(得分:1)

使用df.melt()City列融为一列并进行合并:

m=df1.melt('Name').merge(df2,left_on='value',right_on='City')
#or if you have more columns and need only city: df1.set_index('Name').filter(like='City').reset_index().melt('Name')
m[['Name','CP']]

   Name CP
0  tutu  3
1  titi  2
2  toto  1