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

pandas dataframe to vertica table insertion faster way

我有这样的代码..它工作正常,但将数据加载到 vertica 中花费了太多时间。 1000 行大约 10 分钟。有什么 alternative/faster 方法可以在 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()

谢谢

您应该使用 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 秒对 0.814 秒)。