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!

Pollux
  • 85
  • 1
  • 3
  • 10

1 Answers1

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

Rob Bricheno
  • 4,467
  • 15
  • 29
  • 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 Nov 15 '18 at 14:21
  • @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? – Rob Bricheno Nov 15 '18 at 14:23
  • 1
    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 Nov 15 '18 at 14:38
  • @Pollux no problem, and I'm happy to know it is working for you now :-) – Rob Bricheno Nov 15 '18 at 14:45