我想知道从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()