PostGres 返回数据帧的 MemoryError



我有一个形状为(2183651,127(的数据帧,我想将数据帧存储到PostGres上,但是我不断收到以下错误:

MemoryError: Unable to allocate array with shape (127, 2183651) and data type object

我的系统在 8GB RAM 上运行,并且安装了 Python 64 位。

我正在使用'psql_insert_copy'方法将数据帧推送到数据库;

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://' + str(engine1[2]) + ':' + str(engine1[3]) + '@' + str(engine1[0]) + ':' + str(
engine1[4]) + '/' + str(engine1[1]))
df3.to_sql(tablename, engine, if_exists='append', index=False, method=psql_insert_copy, schema='public')

但是这失败了,这个错误是由于我的硬件规格造成的吗,是否有解决方法?

您可以将迭代器直接传递给copy_expert,而不是将整个数据集具体化为s_buf并传递它。 迭代器需要以 csv 格式返回格式正确的数据行,因此可能需要以某种方式包装才能执行此操作。

最新更新