6

最も効率的な方法で(Python 2.7を使用して) pandas DataFrameをPostgresql DB(9.1)に挿入しようとしています。
「cursor.execute_many」を使用すると、「copy_from」と一緒に「DataFrame.to_csv(buffer,...)」を使用すると非常に遅くなります。
もうたくさん見つけました!パンダで動作するように適応させたWeb上のより高速なソリューション(http://eatthedots.blogspot.de/2008/08/faking-read-support-for-psycopgs.html )。
私のコードは以下にあります。
私の質問は、この関連する質問の方法(「バイナリで標準入力からコピー」を使用)を簡単に転送してDataFrameを操作できるかどうか、およびこれがはるかに高速かどうかです。
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
4

2 に答える 2

1

Pandas データフレームに .to_sql メソッドが追加されました。Postgresql はまだサポートされていませんが、動作するように見えるパッチがあります。ここここの問題を参照してください。

于 2013-09-09T16:13:56.253 に答える
0

私はパフォーマンスをテストしていませんが、次のようなものを使用できるかもしれません:

  1. DataFrame の行を繰り返し処理し、行を表す文字列を生成します (以下を参照)。
  2. たとえばPython を使用して、この iterable をストリームに変換します: Convert an iterable to a stream?
  3. copy_from最後に、このストリームでpsycopg を使用します。

DataFrame の行を効率的に生成するには、次のようなものを使用します。

    def r(df):
            for idx, row in df.iterrows():
                    yield ','.join(map(str, row))
于 2012-05-28T08:41:04.090 に答える