Train Heartnet
Train Heartnet

Reputation: 815

How do I insert a pandas DataFrame to an existing PostgreSQL table?

I have a pandas DataFrame df and a PostgreSQL table my_table. I wish to truncate my_table and insert df (which has columns in the same order) into my_table, without affecting the schema of my_table. How do I do this?

In a rather naive attempt, I tried dropping my_table and then using pandas.DataFrame.to_sql, but this creates a new table with a different schema.

Upvotes: 4

Views: 11644

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210812

I would manually truncate the table and then simply let Pandas do its job:

con.execute('TRUNCATE my_table RESTART IDENTITY;')
df.to_sql('my_table', con, if_exists='append')

Upvotes: 9

Related Questions