I have this code which works fine:
import pandas as pd
import sqldf
df1 = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['Jhon1', 'Jhon2', 'Jhon3']})
df2 = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['Doe1', 'Doe2', 'Doe3']})
sql_query = '''
select * from df1
left join df2
on df1.col1=df2.col1
'''
result_df = sqldf.run(sql_query)
result_df
However when I wrap it inside class function like this:
import pandas as pd
import sqldf
class MyAmazingClass:
def static_function():
df1 = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['Jhon1', 'Jhon2', 'Jhon3']})
df2 = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['Doe1', 'Doe2', 'Doe3']})
sql_query = '''
select * from df1
left join df2
on df1.col1=df2.col1
'''
result_df = sqldf.run(sql_query)
return result_df
df = MyAmazingClass.static_function()
df
I am getting this error:
AttributeError: module 'main' has no attribute 'df2'
How to make this code work in class function?
CodePudding user response:
Use pandasql.sqldf
instead:
import pandas as pd
from pandasql import sqldf
class MyAmaizingClass:
def static_function():
df1 = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['Jhon1', 'Jhon2', 'Jhon3']})
df2 = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['Doe1', 'Doe2', 'Doe3']})
sql_query = '''
select * from df1
left join df2
on df1.col1=df2.col1
'''
result_df = sqldf(sql_query)
return result_df
MyAmaizingClass.static_function()
Output:
col1 col2 col1 col2
0 1 Jhon1 1 Doe1
1 2 Jhon2 2 Doe2
2 3 Jhon3 3 Doe3