Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 699
Train Heartnet Avatar asked Jan 05 '23 17:01

Train Heartnet


1 Answers

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')
like image 78
MaxU - stop WAR against UA Avatar answered Jan 13 '23 12:01

MaxU - stop WAR against UA