如何将 DataFrame 写入 postgres 表? [英] How to write DataFrame to postgres table?

查看:82
本文介绍了如何将 DataFrame 写入 postgres 表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DataFrame.to_sql 方法,但它只适用于 mysql、sqlite 和 oracle 数据库.我无法通过 postgres 连接或 sqlalchemy 引擎传递到此方法.

There is DataFrame.to_sql method, but it works only for mysql, sqlite and oracle databases. I cant pass to this method postgres connection or sqlalchemy engine.

推荐答案

从 pandas 0.14(2014 年 5 月下旬发布)开始,支持 postgresql.sql 模块现在使用 sqlalchemy 来支持不同的数据库风格.您可以为 postgresql 数据库传递 sqlalchemy 引擎(请参阅 docs).例如:

Starting from pandas 0.14 (released end of May 2014), postgresql is supported. The sql module now uses sqlalchemy to support different database flavors. You can pass a sqlalchemy engine for a postgresql database (see docs). E.g.:

from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@localhost:5432/mydatabase')
df.to_sql('table_name', engine)


您是对的,在 0.13.1 版本之前的 Pandas 中不支持 postgresql.如果您需要使用旧版本的 Pandas,这里是 pandas.io.sql 的补丁版本:https://gist.github.com/jorisvandenbossche/10841234.
我之前写过这个,所以不能完全保证它总是有效,但基础应该在那里).如果您将该文件放在工作目录中并导入它,那么您应该能够做到(其中 con 是 postgresql 连接):


You are correct that in pandas up to version 0.13.1 postgresql was not supported. If you need to use an older version of pandas, here is a patched version of pandas.io.sql: https://gist.github.com/jorisvandenbossche/10841234.
I wrote this a time ago, so cannot fully guarantee that it always works, buth the basis should be there). If you put that file in your working directory and import it, then you should be able to do (where con is a postgresql connection):

import sql  # the patched version (file is named sql.py)
sql.write_frame(df, 'table_name', con, flavor='postgresql')

这篇关于如何将 DataFrame 写入 postgres 表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆