如何运行 python sqldf 模块里面的静态函数?
How to run python sqldf module inside static function?
我有这段代码可以正常工作:
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
然而,当我将它包装在 class 函数中时,如下所示:
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
我收到这个错误:
AttributeError: module 'main' has no attribute 'df2'
如何使此代码在 class 函数中工作?
改用pandasql.sqldf
:
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()
输出:
col1 col2 col1 col2
0 1 Jhon1 1 Doe1
1 2 Jhon2 2 Doe2
2 3 Jhon3 3 Doe3
我有这段代码可以正常工作:
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
然而,当我将它包装在 class 函数中时,如下所示:
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
我收到这个错误:
AttributeError: module 'main' has no attribute 'df2'
如何使此代码在 class 函数中工作?
改用pandasql.sqldf
:
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()
输出:
col1 col2 col1 col2
0 1 Jhon1 1 Doe1
1 2 Jhon2 2 Doe2
2 3 Jhon3 3 Doe3