2017-01-09 163 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()))