pandasql is not working in a function python pandas

2.2k Views Asked by At

I am using pandasql to do sql join on pandas dataframe. it's working well without putting them in a function. But after putting everything together in a function, it gave me an error said: NameError: global name 'sqldf' is not defined

the code i am using is like:

import pandasql
def myfunction():
    pandasqldf=lambda q:sqldf(q,globals())
    df=pandasqldf("select * from table1 left join table2 on table1.id=table2.id")

I have tried to use locals() instead, but it's still not working. it would be appreciated for any input or advice on how to solve this problem. Thanks!

1

There are 1 best solutions below

0
On

You didn't include the right import. I also found calling sqldf directly, instead of going through the lambda, to work better. The code below seems to work for me.

from pandasql import sqldf
def select_sql(df_a):
    return sqldf("select * from df_a", locals())

df = pd.DataFrame(np.random.randn(10,10))
select_sql(df)