我在Pandas中使用sqlalchemy来查询postgres数据库,然后将转换结果插入到同一数据库上的另一个表中.但是当我这么做的时候 df.to_sql('db_table2', engine)我收到此错误消息: ValueError: Table 'db_table2' already exists.我注意到它想要创建一个新表.如何将Pandas 数据帧插入到已有的表中?

df = pd.read_sql_query('select * from "db_table1"',con=engine)
#do transformation then save df to db_table2
df.to_sql('db_table2', engine)

ValueError: Table 'db_table2' already exists

推荐答案

使用if_exists个参数:

df.to_sql('db_table2', engine, if_exists='replace')

df.to_sql('db_table2', engine, if_exists='append')

发件人文档字符串:

"""
if_exists : {'fail', 'replace', 'append'}, default 'fail'
    - fail: If table exists, do nothing.
    - replace: If table exists, drop it, recreate it, and insert data.
    - append: If table exists, insert data. Create if does not exist.
"""

Database相关问答推荐

使用存储过程从子表中删除数据

发布 Oracle 和 SQL Server 性能测试是否违反许可?

在 SQL Server 中以编程方式创建数据库

什么技术对处理数百万条记录最有效?

如何使用 SELECT WHERE IN() 保持订单?

苹果 ios 购买收据数据的可能最大长度是多少?

将 `tsv` 文件插入 postgresql 数据库

MySQL JDBC Driver中cachePrepStmts和useServerPrepStmts有什么区别

如何在 MSSQL 2005 中创建递归查询?

ODBC 与 JDBC 与 ADO.NET

NameError:设置更改为 mysql 后未定义名称_mysql

用于 Java 桌面应用程序的最佳数据库是什么

什么是非关系数据库的例子?

在 Firestore 中使用嵌套的单个查询

MySQL 中 NOW()、SYSDATE() 和 CURRENT_DATE() 之间的区别

CouchDB、MongoDB 和 Redis 中的哪个数据库适合从 Node.js 开始?

Twisted + SQLAlchemy 和最好的方法

我应该混淆用户的数据库 ID 吗?

如何在 MySQL 中清理或调整 ibtmp1 文件的大小?

Hibernate hbm2ddl.auto 默认值