0

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.

3
  • You don't return anything from your function Commented Jun 24, 2021 at 14:02
  • Try return table_name at the end of your function. Commented Jun 24, 2021 at 14:37
  • @GordThompson Unfortunately, didn't work. Commented Jun 25, 2021 at 15:17

1 Answer 1

1

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
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.