如何将 Pandas DataFrame 插入现有的 PostgreSQL 表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41740985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:49:13  来源:igfitidea点击:

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

postgresqlpython-3.xpandassqlalchemy

提问by Train Heartnet

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

我有一个 pandas DataFramedf和一个 PostgreSQL table my_table。我想截断my_table和插入df(其中有以相同的顺序列)进入my_table,在不影响的模式my_table。我该怎么做呢?

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

在一个相当幼稚的尝试中,我尝试删除my_table然后使用pandas.DataFrame.to_sql,但这会创建一个具有不同架构的新表。

回答by MaxU

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

我会手动截断表格,然后让 Pandas 完成它的工作:

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