我试图以最有效的方式(使用Python 2.7)将pandas DataFrame插入Postgresql DB(9.1)。
使用" cursor.execute_many"非常慢,#34; DataFrame.to_csv(缓冲区,......)"连同" copy_from"。
我发现已经多了!更快的网络解决方案(http://eatthedots.blogspot.de/2008/08/faking-read-support-for-psycopgs.html),我适应了大熊猫。
我的代码可以在下面找到
我的问题是这个相关问题的方法(使用"使用二进制&#34复制stdin)可以很容易地转移到使用DataFrames,如果这样会快得多。
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
答案 0 :(得分:1)
答案 1 :(得分:0)
我没有测试过性能,但也许你可以使用这样的东西:
copy_from
。要生成DataFrame的行,请使用以下内容:
def r(df):
for idx, row in df.iterrows():
yield ','.join(map(str, row))