python – 将快速pandas数据帧写入postgres

我想知道从pandas DataFrame到postges DB中的数据写入数据的最快方法.

1)我尝试过pandas.to_sql,但由于某种原因它需要实体来复制数据,

2)除了我试过以下:

import io
f = io.StringIO()
pd.DataFrame({'a':[1,2], 'b':[3,4]}).to_csv(f)
cursor = conn.cursor()
cursor.execute('create table bbbb (a int, b int);COMMIT; ')
cursor.copy_from(f, 'bbbb', columns=('a', 'b'), sep=',')
cursor.execute("select * from bbbb;")
a = cursor.fetchall()
print(a)
cursor.close()

但它返回空列表[].

所以我有两个问题:将数据从python代码(数据帧)复制到postgres DB的最快方法是什么?我试过的第二种方法有什么不对?

解决方法:

你的第二种方法应该非常快.

您的代码有两个问题:

>将csv写入f后,您将位于文件末尾.在开始阅读之前,您需要将您的职位回到起点.
>编写csv时,需要省略标题和索引

以下是您的最终代码应如下所示:

import io
f = io.StringIO()
pd.DataFrame({'a':[1,2], 'b':[3,4]}).to_csv(f, index=False, header=False)  # removed header
f.seek(0)  # move position to beginning of file before reading
cursor = conn.cursor()
cursor.execute('create table bbbb (a int, b int);COMMIT; ')
cursor.copy_from(f, 'bbbb', columns=('a', 'b'), sep=',')
cursor.execute("select * from bbbb;")
a = cursor.fetchall()
print(a)
cursor.close()

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...