2

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
  • you just neeeded to change import pandasql to from pandasql import sqldf Commented Oct 26, 2020 at 10:43

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.