繁体   English   中英

使用psycopg2将pandas DataFrame快速插入Postgres DB

[英]Fast insertion of pandas DataFrame into Postgres DB using psycopg2

我试图以最有效的方式(使用Python 2.7)将pandas 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 ),我适应了大熊猫。
我的代码可以在下面找到。
我的问题是这个相关问题的方法(使用“从二进制文件中复制stid”)是否可以轻松转移到使用DataFrames,如果这样会快得多。
使用带有psycopg2的二进制COPY表FROM
不幸的是,我的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,但它有一个看起来有效的补丁。 请在此处此处查看问题。

我没有测试过性能,但也许你可以使用这样的东西:

  1. 通过DataFrame的行迭代,产生一个表示一行的字符串(见下文)
  2. 使用例如Python将此迭代转换为流:将可迭代转换为流?
  3. 最后在此流上使用psycopg的copy_from

要生成DataFrame的行,请使用以下内容:

    def r(df):
            for idx, row in df.iterrows():
                    yield ','.join(map(str, row))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM