pandas dataframe以vertica table插入更快的方式

时间:2018-06-12 17:48:33

标签: python pandas vertica

我有这样的代码..它的工作正常但是花了太多时间将数据加载到vertica中。大约10分钟,1000行。是否有任何替代/更快的方式将数据插入vertica。

import pandas as pd
import vertica_python

conn_info = {'host': '127.0.0.1',
         'user': 'some_user',
         'password': 'some_password',
         'database': 'a_database'}

connection = vertica_python.connect(**conn_info)

df = pd.DataFrame({'User':['101','101','101','102','102','101','101','102','102','102'],'Country':['India','Japan','India','Brazil','Japan','UK','Austria','Japan','Singapore','UK']})

lists= df.values.tolist()

with connection.cursor() as cursor:
    for x in lists:
        cursor.execute("insert into test values (%s,%s)" , x)
        connection.commit()

由于

1 个答案:

答案 0 :(得分:1)

您应该使用cursor.copy选项而不是cursor.execute

例如:

# add new import:
import cStringIO
...
# temporary buffer
buff = cStringIO.StringIO()

# convert data frame to csv type
for row in df.values.tolist():
    buff.write('{}|{}\n'.format(*row))

# now insert data
with connection.cursor() as cursor:
    cursor.copy('COPY test (Country, "User") FROM STDIN COMMIT' , buff.getvalue())

在我的测试系统上跟踪结果

您的实施:

$ time ./so.py
real    0m4.175s
user    0m0.523s
sys 0m0.101s

我的实施:

$ time ./so.py
real    0m0.814s
user    0m0.530s
sys 0m0.078s

快5倍(4.175秒vs 0.814秒)。