如何将 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
How do I insert a pandas DataFrame to an existing PostgreSQL table?
提问by Train Heartnet
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?
我有一个 pandas DataFramedf
和一个 PostgreSQL table my_table
。我想截断my_table
和插入df
(其中有以相同的顺序列)进入my_table
,在不影响的模式my_table
。我该怎么做呢?
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.
在一个相当幼稚的尝试中,我尝试删除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')