将SQL中的条件连接转换为熊猫

时间:2019-07-11 20:34:10

标签: pandas

我该怎么做熊猫? 基本上我有df1,我将加入df2,但是根据df2记录包含的内容,加入键会更改

select coalesce( t2.age,t3.age) as age 
from df1 t1 left join df2 t2 on df1.id=df2.id and df1.Id is not null and df2.id is not null
left join df2 t3 on df1.name = df2.name and df1.name is not null and df2.name is not null and t3.title='Manager'

1 个答案:

答案 0 :(得分:0)

似乎您正在将SQL转换为pandas,仅使用pandasql

import pandas as pd
import pandasql as ps

q1 = """select coalesce( t2.age,t3.age) as age 
from df1 t1 left join df2 t2 on df1.id=df2.id and df1.Id is not null and df2.id is not null
left join df2 t3 on df1.name = df2.name and df1.name is not null and df2.name is not null and t3.title='Manager' """

print(ps.sqldf(q1.replace('\n',''), locals()))