python - PostGres 为数据帧返回 MemoryError

标签 python python-3.x postgresql dataframe

我有一个形状为 (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/

相关文章:

postgresql - Postgres SQL - 使用 OR 与 || 的 LIKE 查询的不同结果

Python 3.5 字典比较

python-3.x - 更改数据表示后维度不匹配 "LabelBinarizer "

python - 按顺序指定数量的 1 和 0 的 Numpy 数组

Python 正则表达式

python - 创建并返回具有连续重复字母的所有国家/地区的元组

sql - 如何在查询中使用 (func()).* 语法避免多个函数求值?

sql - 如何在删除命令上添加条件?

python - cython 函数中的 Lambda 表达式

python - 如何在2个不同帐户的S3存储桶之间复制特定文件