有DataFrame.to_sql方法,但它只适用于mysql,sqlite和oracle数据库。我不能传递给这种方法postgres连接或sqlalchemy引擎。
从pandas 0.14(2014年5月底发布)开始,支持postgresql。 sql
模块现在使用sqlalchemy
来支持不同的数据库风格。您可以为postgresql数据库传递sqlalchemy引擎(请参阅docs)。例如。:
from sqlalchemy import create_engine
engine = create_engine('postgresql://scott:tiger@localhost:5432/mydatabase')
df.to_sql('table_name', engine)
你是正确的,在pandas到0.13.1版本的postgresql不支持。如果您需要使用旧版本的pandas,这里是pandas.io.sql
的补丁版本:https://gist.github.com/jorisvandenbossche/10841234。
我前一段时间写过这篇文章,所以不能完全保证它始终有效,但基础应该在那里)。如果您将该文件放在工作目录中并导入它,那么您应该可以这样做(其中con
是postgresql连接):
import sql # the patched version (file is named sql.py)
sql.write_frame(df, 'table_name', con, flavor='postgresql')
更快的选择:
以下代码将您的Pandas DF复制到postgres DB比df.to_sql方法快得多,您不需要任何中间csv文件来存储df。
根据您的数据库规范创建引擎。
在postgres DB中创建一个与Dataframe(df)列数相同的表。
DF中的数据将插入到postgres表中。
from sqlalchemy import create_engine
import psycopg2
import io
如果你想要替换表,我们可以使用来自df的标头用普通的to_sql方法替换它,然后将整个耗时的df加载到DB中。
engine = create_engine('postgresql+psycopg2://username:password@host:port/database')
df.head(0).to_sql('table_name', engine, if_exists='replace',index=False) #truncates the table
conn = engine.raw_connection()
cur = conn.cursor()
output = io.StringIO()
df.to_csv(output, sep='\t', header=False, index=False)
output.seek(0)
contents = output.getvalue()
cur.copy_from(output, 'table_name', null="") # null values become ''
conn.commit()
我就是这样做的,因为它使用的是execute_batch,所以我可能会更快:
# df is the dataframe
if len(df) > 0:
df_columns = list(df)
# create (col1,col2,...)
columns = ",".join(df_columns)
# create VALUES('%s', '%s",...) one '%s' per column
values = "VALUES({})".format(",".join(["%s" for _ in df_columns]))
#create INSERT INTO table (columns) VALUES('%s',...)
insert_stmt = "INSERT INTO {} ({}) {}".format(table,columns,values)
cur = conn.cursor()
cur = db_conn.cursor()
psycopg2.extras.execute_batch(cur, insert_stmt, df.values)
conn.commit()
cur.close()
熊猫0.24.0+解决方案
在Pandas 0.24.0中,引入了一个专门为Postgres快速写入而设计的新功能。你可以在这里了解更多信息:https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method
import csv
from io import StringIO
from sqlalchemy import create_engine
def psql_insert_copy(table, conn, keys, data_iter):
# gets a DBAPI connection that can provide a cursor
dbapi_conn = conn.connection
with dbapi_conn.cursor() as cur:
s_buf = StringIO()
writer = csv.writer(s_buf)
writer.writerows(data_iter)
s_buf.seek(0)
columns = ', '.join('"{}"'.format(k) for k in keys)
if table.schema:
table_name = '{}.{}'.format(table.schema, table.name)
else:
table_name = table.name
sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(
table_name, columns)
cur.copy_expert(sql=sql, file=s_buf)
engine = create_engine('postgresql://myusername:mypassword@myhost:5432/mydatabase')
df.to_sql('table_name', engine, method=psql_insert_copy)