4

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.

1 Answer 1

9

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')
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the quick response! Could you tell me what the 'RESTART IDENTITY' bit does? I did refer the PostgreSQL docs just now, but couldn't understand what it means; "Automatically restart sequences owned by columns of the truncated table(s)".
@TrainHeartnet, you may want to read about PostgreSQL sequnces. You can omit RESTART IDENTITY if you don't have sequences in the my_table table
You could skip the manual truncation and do a single line: df.to_sql('my_table', con, if_exists='replace')
What if I need to execute an UPSERT statement?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.