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

Art*_*r G 6 python postgresql psycopg2 pandas

我正在尝试以最有效的方式(使用Python 2.7)将pandas DataFrame插入Postgresql DB(9.1)中。
使用“ cursor.execute_many”的速度确实很慢,因此“ DataFrame.to_csv(buffer,...)”和“ copy_from”一起使用也很慢。
我已经发现了很多!我适应了与熊猫一起使用的Web上更快的解决方案(http://eatthedots.blogspot.de/2008/08/faking-read-support-for-psycopgs.html)。
我的代码可以在下面找到。
我的问题是,这个相关问题的方法(使用“使用二进制从stdin复制”)是否可以轻松地转移到DataFrames上使用,并且这样做是否会更快。
将二进制COPY表FROM与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
Run Code Online (Sandbox Code Playgroud)

lbo*_*lla -1

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

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

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

    def r(df):
            for idx, row in df.iterrows():
                    yield ','.join(map(str, row))
Run Code Online (Sandbox Code Playgroud)