将pandas数据帧快速写入postgres

2024-10-05 14:23:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道最快的方式将数据从pandas DataFrame写到postgesdb中的表中。在

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代码(dataframe)复制数据到postgres数据库的最快方法是什么?我尝试过的第二种方法有什么不对?在


Tags: to数据方法fromio实体dataframepandas
1条回答
网友
1楼 · 发布于 2024-10-05 14:23:57

你的第二种方法应该很快。在

您的代码有两个问题:

  1. 将csv写入f后,您将被定位到文件的末尾。在开始阅读之前,你需要把你的立场放回开头。在
  2. 写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()

相关问题 更多 >