1

I'm looking for a way to create a postgres table from a pandas dataframe, and then read the postgre table directly in pgAdmin. I've found a way to do that thanks to this link : How to write DataFrame to postgres table? .

The command is :

from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@host:port/database')
df.to_sql('table_name', engine)

However, I don't know what is 'table_name'. Do I have to create a table in my Data Base?

Thanks for your help!

1 Answer 1

3

A table with the name you specify will be created if it does not already exist. https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html

Sign up to request clarification or add additional context in comments.

4 Comments

Ok, the thing is that I have an error : NameError: name 'bat_prediction_rf' is not defined . The last lign of my code is baonotnull_test.to_sql(bat_prediction_rf, engine) . Maybe it's because of the schema. I explain ; I would like to create a table names 'bat_prediction_rf' in the schema p_baobat itself in the database db. I don't understand why I have this error...
@Pollux should that be baonotnull_test.to_sql('bat_prediction_rf', engine) (note here 'bat_prediction_rf' is a string) or is bat_prediction_rf a variable defined somewhere else in your code?
You're right, bat_prediction_rf isn't defined in my code, I have to write 'bat_prediction_rf'. Thank you very much it's working! Sorry for disturbing you.
@Pollux no problem, and I'm happy to know it is working for you now :-)

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.