2017-01-09 168 views
4

我有一个1,000,000 X 50熊猫DataFrame,我目前正在写使用SQL表:加速Pandas to_sql()?

df.to_sql('my_table', con, index=False)

它需要一个非常长的时间。我已经看到了关于如何加速这个过程的各种解释,但是他们似乎都不适用于MSSQL。

  1. 如果我尝试的方法:

    Bulk Insert A Pandas DataFrame Using SQLAlchemy

    然后我得到一个no attribute copy_from错误。

  2. 如果我尝试从多线程操作方法:

    http://techyoubaji.blogspot.com/2015/10/speed-up-pandas-tosql-with.html

    然后我得到一个QueuePool limit of size 5 overflow 10 reach, connection timed out错误。

是否有任何简单的方法来加速to_sql()到MSSQL表?无论是通过大量复制或其他方法,但完全从Python代码?

+0

您正在写入现有表还是将其创建? – MaxU

+0

我会使用[this](http://stackoverflow.com/a/33817026/5741205)或类似的方法 - BCP应该快速__very__ – MaxU

回答

0

我已经使用ctds来做一个批量插入,使用SQL服务器的速度要快很多。在下面的例子中,df是pandas DataFrame。 DataFrame中的列序列与mydb的架构相同。

import ctds 

conn = ctds.connect('server', user='user', password='password', database='mydb') 
conn.bulk_insert('table', (df.to_records(index=False).tolist()))