I am trying to use Pandas' read_sql() (from sqlalchemy) inside a function, but it keeps returning string instead of a DataFrame.
Why is this happening and how it can be fixed?
When I do something like this:
table_name = pd.io.sql.read_sql(table_name, con=engine)
Everything works perfectly. But when I put the same in a function like this one:
def sql_reading(table_name, comment):
table_name = pd.io.sql.read_sql(table_name, con=engine)
print('\x1b[1;31m'+comment +'\x1b[0m')
table_name.info()
return table_name
It returns with info about the DataFrame, but does not allow to me to use the result as a DataFrame:
sql_reading(some_table_from_a_query, "Some comment")
Prints some_table_from_a_query.info(), everything is fine.
But when I try to print out its head or tail, or use describe() literally in the next step, it returns with an error:
some_table_from_a_query.info()
AttributeError: 'str' object has no attribute 'info'
UPD: Return table_name didn't make any difference.
Would appreciate an explanation on why it happens and how to fix it.
You are confusing the string 'table_name' with the actual dataframe, which you have also called 'table_name'. That's why you get the error that string (table_name) has no attribute 'info'. Try using different variable names for the table versus the dataframe, such as:
def sql_reading(table_name, comment):
df_table_name = pd.io.sql.read_sql(table_name, con=engine)
print('\x1b[1;31m'+comment +'\x1b[0m')
df_table_name.info()
return df_table_name
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.