我有一个形状为 (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 格式返回格式正确的数据行,因此可能需要以某种方式进行包装才能做到这一点。
关于python - PostGres 为数据帧返回 MemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58317206/