我想使用POLARS将地块文件中的数据框存储到PostgreSQL中,代码如下:

def store_in_postgresql(df):
    password = 'anon'
    username = 'postgres'
    database = 'nyc_taxis'
    uri = f'postgresql://{username}:{password}@localhost:5432/{database}'
    engine = create_engine(uri)
    common_sql_state = "SQLSTATE: 42P07"
    
    try:
        df.write_database(table_name, connection=uri,
                          engine='adbc', if_exists='replace')
        print('loading has been completed!')
    except Exception as e:
        if(common_sql_state in str(e)):
            df.write_database(table_name, connection=uri,
                          engine='adbc', if_exists='append')
            print('loading has been completed!')
        else:
            print(e)

但我得到了这样的错误:

INVALID_ARGUMENT: [libpq] Failed to execute COPY statement: PGRES_FATAL_ERROR ERROR:  COPY file signature not recognized
. SQLSTATE: 22P04

代码存储小尺寸的数据帧,如400万行(200mb),但当我想存储1800万行(500mb)的 Big Data 帧时,我得到了上面的错误,有没有方法修复代码或可能切片数据帧以将其存储在数据库中?提前谢谢你.

推荐答案

我想我已经弄明白了,这是记忆问题. 由于该函数适用于较小的数据帧而不是较大的数据帧,因此我创建了一个新函数,将大型数据帧分割成较小的区块,然后由上面的函数进行处理:

def store_by_chunking(df, num_of_chunks):
try:
    length = len(df) // num_of_chunks
    j = 0
    list_of_chunks = []
    
    for i in range(num_of_chunks):
        list_of_chunks.append(j)
        j += length
    list_of_chunks.append(len(df))
    
    print(list_of_chunks)
    
    for i in range(num_of_chunks):
        sliced_df = df.slice(list_of_chunks[i], list_of_chunks[i+1])
        store_in_postgresql(sliced_df)
except Exception as e:
    print(e)

这段代码到目前为止还没有给我一个错误,希望它能帮助有同样问题的人.

Postgresql相关问答推荐

利用PostgreSQL查询中表的顺序来计算包含每次时间的时间范围

Postgres-pgloader-默认情况下,在PostgreSQL中将列名转换为小写

列索引8上的扫描错误,名称已复制:不支持扫描,正在存储驱动程序.值类型[]uint8到类型*[]*bool

时间戳的postgreSQL-to_char如果为零,则不显示微秒

右连接 postgresql 出现语法错误

在 Windows 上使用 rsync 进行 Postgresql 副本升级

有没有办法共享数据或监控复杂 PostgresQL 事务的进度?

使用间隔参数的 go postgres 准备好的语句不起作用

无法从在 wsl 2 上运行的服务之一连接到在 wsl 2 上的容器中运行的 postgres 数据库

如何使用 SQLAlchemy 将列默认设置为 PostgreSQL 函数?

?(问号)运算符在 Rails 中查询 Postgresql JSONB 类型

IntegrityError:postgres 从转储恢复后,所有具有 ForeignKey 的模型/字段的id列中的空值

在 postgresql 中将 bool 转换为 int

如何删除 Postgres 上的所有数据库?

Postgres Npgsql 连接池

如何从 CSV 为 PostgreSQL 副本生成模式

有没有办法确保 WHERE 子句在 DISTINCT 之后发生?

错误:关系列不存在 PostgreSQL,无法运行插入查询

使用 Postgres 在 Rust 的 Diesel 库中添加时间戳

使用 PostgreSQL 的 Linq To Sql