python - 使用 psycopg2 将 pandas DataFrame 快速插入到 Postgres DB 中

标签 python postgresql psycopg2 pandas

我正在尝试插入 pandas以最有效的方式(使用 Python 2.7)将 DataFrame 转换为 Postgresql DB (9.1)。
使用“cursor.execute_many”真的很慢,“DataFrame.to_csv(buffer,...)”和“copy_from”也是如此。
我发现了一个已经很多了!网络上更快的解决方案 ( http://eatthedots.blogspot.de/2008/08/faking-read-support-for-psycopgs.html ) 我适应了与 Pandas 一起工作。
我的代码可以在下面找到。
我的问题是这个相关问题的方法(使用“使用二进制从标准输入复制”)是否可以很容易地转移到与数据帧一起工作,如果这样会更快。
Use binary COPY table FROM with psycopg2
不幸的是,我的 Python 技能不足以理解这种方法的实现。
这是我的方法:


import psycopg2
import connectDB # this is simply a module that returns a connection to the db
from datetime import datetime

class ReadFaker:
    """
    This could be extended to include the index column optionally. Right now the index
    is not inserted
    """
    def __init__(self, data):
        self.iter = data.itertuples()

    def readline(self, size=None):
        try:
            line = self.iter.next()[1:]  # element 0 is the index
            row = '\t'.join(x.encode('utf8') if isinstance(x, unicode) else str(x) for x in line) + '\n'
        # in my case all strings in line are unicode objects.
        except StopIteration:
            return ''
        else:
            return row

    read = readline

def insert(df, table, con=None, columns = None):

    time1 = datetime.now()
    close_con = False
    if not con:
        try:
            con = connectDB.getCon()   ###dbLoader returns a connection with my settings
            close_con = True
        except psycopg2.Error, e:
            print e.pgerror
            print e.pgcode
            return "failed"
    inserted_rows = df.shape[0]
    data = ReadFaker(df)

    try:
        curs = con.cursor()
        print 'inserting %s entries into %s ...' % (inserted_rows, table)
        if columns is not None:
            curs.copy_from(data, table, null='nan', columns=[col for col in columns])
        else:
            curs.copy_from(data, table, null='nan')
        con.commit()
        curs.close()
        if close_con:
            con.close()
    except psycopg2.Error, e:
        print e.pgerror
        print e.pgcode
        con.rollback()
        if close_con:
            con.close()
        return "failed"

    time2 = datetime.now()
    print time2 - time1
    return inserted_rows

最佳答案

Pandas 数据框现在有一个 .to_sql 方法。目前还不支持 Postgresql,但有一个看起来可以正常工作的补丁。查看问题herehere .

关于python - 使用 psycopg2 将 pandas DataFrame 快速插入到 Postgres DB 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9826431/

相关文章:

python - Plotly:如何在指定阈值的折线图上显示不同的颜色段?

Python 函数输入

mysql - 不支持源数据类型 [geometry]

python - 如何模拟 psycopg2 光标对象?

python - Pandas 遍历指定行号的行

python - 找到双线;更快的方法

arrays - 为什么这些连接根据大小不同?

node.js - 尝试以多对多关系创建一个实例和多个相关实例

python - 我如何使用 Psycopg2 的 LoggingConnection?

python - PostgreSQL 不使用 psycopg2 在 AWS Lambda 上的 Python 中插入